PROBLEM SET 3: OUTDATED | SOLUTION (CS50 PYTHON)

preview_player
Показать описание


––– DISCLAIMER –––

The following videos are for educational purposes only. Cheating or any other activities are highly discouraged!! Using another person’s code breaks the academic honesty guidelines. This solution is for those who have finished the problem sets and want to watch for educational purposes, learning experience, and exploring alternative ways to approach problems and is NOT meant for those actively doing the problem sets. All problem sets presented in this video are owned by Harvard University.

–––
Рекомендации по теме
Комментарии
Автор

To fix the problem of receiving "September 8 1636" you need to check if the user is giving the date in the correct format. So, before line 35 you need to add the following code:
if not old_day.endswith(", "):
continue
This way you will check if the date is in the correct format and prompt the user again.

DorsCodingSchool
Автор

if (1 <= int(month) <= 12) and (1 <= int(day) <= 31):

KofyImages
Автор

Thanks for your videos! I'm following the CS50 class and after I finish each problem set I always check your solution too! 😊

I leave my solution here too, I used a dictionary to add a value to each month. Don't know if it's the best method to create a dictionary, but it is working, so...

months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]

dmon = {}
j = 1
for i in months:
dmon[i] = j
j += 1

def main():
while True:
date = input("Date: ")
if "/" in date:
try:
m, d, y = date.split("/")
if int(m) < 1 or int(m) > 12 or int(d) < 1 or int(d) > 31:
pass
else:

break
except:
pass
elif ", " in date:
try:
m, d, y = date.split(" ")
d = d.removesuffix(", ")
if int(d) < 0 or int(d) > 31:
pass
elif m not in months:
pass
else:

break
except:
pass
main()

massimotarsitani
Автор

fiz de outra forma, vlw pelo video:

def main():
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
reverse(months)

def reverse(months):
while True:
try:
date = input("Date: ").strip()
if ', ' in date:
date = date.capitalize()
month, day, year = date.split()
day = day.split(', ')
day = int(day[0])
if month in months and day >= 1 and day <= 31:
return

elif '/' in date:
month, day, year = date.split('/')
year = int(year)
day = int(day)
month = int(month) - 1
if month in range(len(months)) and day >= 1 and day <= 31:
return
except ValueError:
pass

main()

danielvictorbarbosasilva
Автор

I got the following code:

months = {
"January": 1,
"February": 2,
"March": 3,
"April": 4,
"May": 5,
"June": 6,
"July": 7,
"August": 8,
"September": 9,
"October": 10,
"November": 11,
"December": 12
}

while True:
date = input().title()
month, day, year = date.replace("/", " ").replace(", ", "").split(" ")
dd = int(day)
yyyy = int(year)
if month.isnumeric():
mm = int(month)
if not 1 <= mm <= 12 and 1 <= dd <= 31:
print("Invalid date.")
continue
else:

break
if month in months:
if not 1 <= dd <= 31:
print("Invalid date.")
continue
else:

break

sausagebaps
Автор

this problem is kicking my ass lol i spent two days trying to figure it out. got like 90% of the way and was still failing 2 check50s. this video helped. thanks! i dont why the try and except with inside conditionals still end up confusing me. frustrating but hopefully i get it at some point. i ended up copying someones code and having ai explain every step. Going to start over and try it again.

Jim-uk
Автор

To everyone whose code is showing invalid for September 8 1636 (due to space) :
Easiest way to get rid of it is to add single line of code given below (after second try: inside first except:) also indent everything inside it till next except: arrives -

Code - - - if ", " in date:

heyaniruddh
Автор

Hello, wouldn't be easier to find the month number like this:
if old_month in months:
month = months.index(old_month) + 1

Just another way to make it.

RoyRodriguezS
Автор

Thanks for posting these, they are very helpful. I think i've condensed the 3 lines of "for i in range(len(months)):" into one line. I wrote

month = int(months.index(old_month)) + 1
If someone sees a bug in my alternate solution please comment!

jaspz
Автор

is mine readable/understandable?

months_list = [
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
]

while True:
# Prompt the user for a date formatted like 9/8/1636 or September 8, 1636
answer = input("Date: ").strip().title()

# For inputs like 9/8/1636
if "/" in answer:
try:
month, day, year = answer.split("/")
month = int(month)
day = int(day)
except ValueError:
pass
else:
if month <= 12 and day <= 31:

# The format :02 adds a zero to single digits
break

# For inputs like September 8, 1636
elif ", " in answer:
month, day, year = answer.split()
try:
day = int(day.replace(", ", ""))
except ValueError:
pass
else:
if day <= 31:
for i in range(len(months_list)):
if month == months_list[i]:
month = f"{(i+1):02}"
# i+1 because the list is zero-indexed

break

luanpires
Автор

good job! I struggled with the ", " part but finally come up with pretty weird way (in short i checked if first character in date is alphabetic and if date[-6] equal, lol. I knew its not optimal way of solving this so I wanted to look for simpler ways. Nice video

infisspablo
Автор

If you're looking for another way of validating if day and month are "real" involving range and list functions:
if int(dd) in list(range(32)) and int(mm) in list(range(13))

kyrylldmytrenko
Автор

This is what I did

def main():
date = input("Date: ").strip().title()
find(date)

months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]

def find(date):
while True:
try:
if(date not in months):
date = str(date)
mm, dd, yyyy = date.split("/")
mm = int(mm)
dd = int(dd)
if(mm < 12 and dd < 32):

break
else:
main()

except ValueError:
if(", " in date and date[0:2].isalpha()):
month, year = date.split(", ")
month, day = month.split(" ")
day = int(day)
if(month in months and day<32):

else:
main()
else:
main()
break
main()

fruityloops
Автор

i guess im the only one that used the datetime function so i dont have to check wether or not the user input more than 31 days or months because the function gives an error that you can catch with except

TrismegistusH
Автор

Try This

months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
def main():
while True:
date = input('Date: ')
try:
mnth, day, year = date.split('/')
mnth = int(mnth)
day = int(day)
year = int(year)
if (int (mnth) > 0 and int(mnth) < 13) and (int(day) > 0 and int(day) < 32):
if year >= 1000 and year <= 9999:
print (year, f'{mnth:02}', f'{day:02}', sep='-')
break
except:
try:
if ", " in date:
mnth, day, year = date.split(' ')
day = day.replace(', ', '')
day = int(day)
year = int(year)
if mnth in months and (int(day) > 0 and int(day) < 32):
if year >= 1000 and year <= 9999:
mnth= (months.index (mnth)+1)
print (year, f'{mnth:02}', f'{day:02}', sep = '-')
break
except:
pass

main()

thetechmask
Автор

Managed to do this all on my own, will watch your video and explanation in a bit. Posted my solution below as reference, think the code is ugly and inefficient as heck (especially the "switch: False" part to break out of the for-loop) but it passed the tests.

month = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]

while True:
try:
date = input("Date: ")
count = 0

if "/" in date:
x, y, z = date.split("/")
x = int(x)
y = int(y)
z = int(z)

if y >= 1 and y <= 31 and x >= 1 and x <= 12:
print(f"{z:02}" + "-" + f"{x:02}" + "-" + f"{y:02}")
break

else:
pass

switch = False
for i in month:
count = count + 1
if i in date:
new_count = str(count)
i = date.replace(i, new_count)
j = i.replace(", ", "")
a, b, c = j.split(" ")
a = int(a)
b = int(b)
c = int(c)
if a >= 1 and a <= 31 and b >= 1 and b <= 12:
print(f"{c:02}" + "-" + f"{a:02}" + "-" + f"{b:02}")
switch = True
break
else:
pass

if switch: break
if switch: break

except ValueError:
pass

cruseder
Автор

My version of code

months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

while True:
try:

# takig user input
date = input("Date: ").strip()

# check if first charcter of string is not letter for (September 1, 1999)
if not date[0].isdigit():

# split the input string into month_day and year
month_day, year = date.split(", ")

# split the month_day string into month and day
month, day = month_day.split(" ")

# if day are between 1 - 31 print the output
if (1<= int(day) <= 31):

break
else:

# split the input string into month day and year
month, day, year = date.split("/")

# check if month is between 1-12 and day is between 1-31 print the output
if (1 <= int(month) <= 12) and (1 <= int(day) <=31):

break

except:
pass

mshamaz
Автор

I added a small portion of code to catch a date if the user incidentally put the month in the 2nd column such as " 8 September 2023".
I could have condensed the code a bit more, but I thought it would impact readability too much.

months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]

def main():

while True:

# While input is not in correct format - keep looping
date = input("Date: ")

# Try first seeing if date follows format of mm/dd/yyyy
try:

month, day, year = date.split("/")

month = int(month)
day = int(day)
year = int(year)

if 0 < month <= 12 and 0 <= day <= 31 and year >= 0:



# Should that fail - try seeing if date entered in alternative format
# What ultimately determines if the program sees this as a date is if one of the first two words matches a key in our months list
except:

try:

if ", " in date:

date = date.replace(", ", "")

month, day, year = date.split(" ")

# If month was first word given ex: September 8, 1636
if month.title() in months:

month = months.index(month) + 1

month = int(month)
day = int(day)
year = int(year)

if 0 < month <= 12 and 0 <= day <= 31 and year >= 0:



# If month was second word given ex: 8 September 2023
elif day.title() in months:

day = months.index(day) + 1

month = int(month)
day = int(day)
year = int(year)

if 0 < day <= 12 and 0 <= month <= 31 and year >= 0:



except:

pass

main()

jknids
Автор

So I understand everything except the flow of the try and excepts. What was that failed on your first try that went to the nested one? The split? I guess there were no /? Would that trigger an error? Why is the second try nested inside the except? Damn tries why are they so weird.
I also saw the example run it prompts again on certain cases, your input is not inside a try

Hellmiauz
Автор

Hello i have this problem and i cant seem ti find the solution...
input of " 9/8/1636 " outputs 1636-09-08
expected "1636-09-08", not "1636 -09-08"

juanb