You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50p 2022版Problem 3「Outdated」Check50单一测试用例失败求助

CS50p 2022版Problem 3「Outdated」Check50单一测试用例失败求助

嘿,我帮你看了下你的代码和问题描述,发现问题大概率出在输入空格的处理上——虽然你用了strip()处理整个输入字符串,但Check50的测试用例可能存在一些你没考虑到的空格场景,导致程序没走到输出逻辑。

你提到手动输入9/8/1636正常,但Check50输入9/8/1636 (末尾带空格)时无输出。虽然你的代码里用了strip(),但如果strip()之后的字符串分割后,某个字段还残留空格(比如极端情况:输入是9/ 8 / 1636,strip()处理后中间的空格还在),不过你的情况里是末尾空格,strip()应该能去掉,但可能是代码的条件判断流程里有隐藏的问题?

不过更稳妥的做法是,在分割日期字段后,单独对每个字段做strip()处理,避免任何多余空格干扰类型转换和条件判断。下面是优化后的代码片段:

优化后的核心代码

# This List include Month spelled in letter/word format
month_a = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
]

def main():
    while True:
        try:
            x = input("Date: ").title().strip() 
            if "/" in x: # check if user input format is mm/dd/yyyy
                # 先确保分割后是三个有效部分
                parts = x.split("/")
                if len(parts) != 3:
                    continue
                month, day, year = parts
                # 单独清除每个字段的多余空格
                month = month.strip()
                day = day.strip()
                year = year.strip()
                # 统一做类型转换,避免分散判断的冗余
                m = int(month)
                d = int(day)
                y = int(year)
                # 合并条件判断,逻辑更清晰
                if 1 <= m <= 12 and 1 <= d <= 31 and 0 <= y <= 9999:
                    print(f"{y:04}-{m:02}-{d:02}")
                    break 
            elif "," in x: # check if user input format is mm dd, yyyy
                parts = x.split(" ")
                if len(parts) != 3:
                    continue
                month_str, day_str, year = parts
                # 处理日期的逗号和多余空格
                day_str = day_str.replace(',', '').strip()
                month_str = month_str.strip()
                year = year.strip()
                d = int(day_str)
                y = int(year)
                if month_str in month_a:
                    m = month_a.index(month_str)+1
                    if 1 <= d <= 31 and 0 <= y <= 9999:  
                        print(f"{y:04}-{m:02}-{d:02}")
                        break 
        except ValueError:
            pass

main()

优化说明

  1. 先校验分割结果:确保输入分割后是预期的3个字段,避免因格式错误触发不必要的异常
  2. 单独处理字段空格:对每个分割后的字段单独执行strip(),彻底清除首尾多余空格,避免类型转换或条件判断出错
  3. 简化条件判断:把分散的条件判断合并,减少嵌套层级,让逻辑更易读
  4. 精简异常捕获:只保留必要的ValueError捕获,UnboundLocalError可以通过提前校验分割结果避免

这样修改后,不管输入的日期前后、中间有没有多余空格,程序都能正确处理,应该能通过Check50的那个测试用例了。你可以试试看!

备注:内容来源于stack exchange,提问作者RL_learning_python

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:18:02