Skip to content

feat: porting e implementazione ex2 da cpp a python #166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/ex2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Improve this program replacing if/else if with an array.


def day_of_the_week():
# Input week number from user
weekDay = int(input("Enter week number(1-7): "))
daysOfTheWeek = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
]
MIN_NUMBER = 1
MAX_NUMBER = 8
if weekDay not in range(MIN_NUMBER, MAX_NUMBER): # range usa un intervallo [a,b[
Copy link
Collaborator

@TendTo TendTo Nov 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Questa sintassi e' estremamente espressiva, ma devo fare l'avvocato del diavolo e farti notare che e' una operazione estremamente inefficiente, in quanto stai iterando sopra un generatore fino a trovare il valore scelto (o fino alla fine, se non presente). Se i valori fossero molto pi' grandi sarebbe uno spreco enorme.
Una alternativa semplice ma a complessita' costante sarebbe:

if not MIN_NUMBER <= weekDay < MAX_NUMBER: # Se inverti il corpo di if ed else puoi anche rimuovere il not

Giusto per tua curiosita', puoi provare ad eseguire questo script e vedere tu stesso:

from timeit import default_timer as timer

MIN_NUMBER = 1
MAX_NUMBER = 100000000000000000000000000000000000000000000
weekDay = -1

start = timer()
if weekDay not in range(MIN_NUMBER, MAX_NUMBER):
    print("Error: Invalid day of the week")
end = timer()
print(end - start) # 2.203899905201979e-05

start = timer()
if not MIN_NUMBER <= weekDay < MAX_NUMBER:
    print("Error: Invalid day of the week")
end = timer()
print(end - start) # 2.132998583372682e-06 (un'ordine di grandezza piu' veloce!)

print("Error: number not in expected range (1 through 7), retry.")
else:
print(f"Selected day: {daysOfTheWeek[weekDay-1]}")


day_of_the_week()