CS50P PSET 3 "Outdated": I am failing one testcase

106 views Asked by At

I'm attempting this problem: https://cs50.harvard.edu/python/2022/psets/3/outdated/ which is basically a program that takes input in "month/day/year" format or "month day, year" format and outputs in YYYY-MM-DD format. After running my code through check50 (a program that tests your code), I passed all the conditions except 1: "input of September 8 1636 results in reprompt" Do I make the program require the "," be in the date?

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

while True:
    try:
        date = input("Date: ")
        month, day, year = date.split("/")
        if (int(month)>=1 and int(month)<=12) and ( 1 <= int(day) <= 31):
            day = int(day)
            if day < 10:
                day = f"{int(day):02}"
            if int(month) <10:
                month = f"{int(month):02}"
            break
    except(ValueError):
        try:
            month, day, year = date.split(" ")
            day = day.strip(",")
            if month in months and ( 1 <= int(day) <= 31):
                for m in months:
                    if m == month:
                        month = months.index(m) + 1
                        month = f"{int(month):02}"
                day = f"{int(day):02}"
                break
        except:
            pass
print(f"{year}-{month}-{day}")
1

There are 1 answers

0
Ariana P On

First off, I'll note that testing your code on my system, it works and gives the correct reformatted date for the input September 8 1636 and September 8, 1636

However, I'd like to still answer your question - how can you make the code require input with the comma like September 8, 1636?

I would add a condition to check that the input matches the two formats you specified, using regular expressions - this solves your problem, and also it's good practice to check your inputs.

import re
#... your  other imports and definitions

format1 = re.compile(r"\d{2}/\d{2}/\d{4}") # matches MM/DD/YYYY, but not M/D/YYYY
format2 = re.compile(r"[A-Z][a-z]+ \d{1,2}, \d{4}") # matches format like September 8, 1640

if format1.match(date):
#(your first try-except)

elif format1.match(date):
#(your second try-except)

else:
print("Format does not match") #or however else you like to show errors/debug