CS50P PSET3 Outdated问题:输入September 8 1636未触发重输排查
CS50P 2022作业集3 Outdated题目问题解答
问题描述
正在完成CS50P 2022年作业集3的Outdated题目,该题目要求程序接收「月/日/年」或「月 日, 年」格式的日期输入,转换为YYYY-MM-DD格式输出。使用check50测试代码后,所有测试用例仅「输入September 8 1636需触发重新输入」未通过,请问是否需要强制日期中必须包含逗号?
用户提供的代码
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}")
解答
结论
是的,必须强制第二种格式包含逗号。题目明确要求的格式是「月 日, 年」,逗号是格式的一部分,输入September 8 1636(无逗号)属于不符合要求的输入,程序应该触发重新输入,你的代码正是因为没有拦截这种情况才导致测试失败。
问题原因
你的代码中用day = day.strip(",")处理日期,这会把带逗号的8,转成8,但如果输入本身没有逗号(比如September 8 1636),day本身就是8,strip(",")不会改变它,后续代码会默认这个输入合法并继续处理,没有进入重新输入的逻辑。
修复方案
在处理第二种格式时,先检查原始的day部分是否包含逗号,只有包含逗号的情况下才继续处理,否则主动抛出异常,让程序回到循环等待正确输入。修改后的核心代码如下:
except(ValueError): try: month, day, year = date.split(" ") # 检查day是否包含逗号,不符合则触发异常 if "," not in day: raise ValueError day = day.strip(",") if month in months and (1 <= int(day) <= 31): # 简化月份查找逻辑 month = f"{months.index(month) + 1:02}" day = f"{int(day):02}" break except: pass
另外,你原来的月份查找循环可以简化,直接用months.index(month)+1获取月份数字,不需要遍历整个列表。
修改后,当输入September 8 1636时,程序会检测到day中没有逗号,触发异常后继续循环,等待用户输入符合格式的日期,就能通过对应的check50测试用例。
内容的提问来源于stack exchange,提问作者user23145167
相关产品推荐
相关产品推荐

