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

CS50 Python Pset3 Outdated问题:日期转换代码调试求助

问题分析与修复方案

你的代码核心问题是没有严格验证输入格式是否符合作业要求的两种标准美式日期格式,同时缺少日期合法性的完整校验,导致不符合要求的输入被错误放行。

原代码的关键缺陷

  1. 格式处理过于随意:你统一将输入中的空格替换为/,导致混合格式(比如October/9/1701这种单词月份+斜杠分隔的非标准格式)被错误识别为有效格式;而像September 8 1636这种缺少逗号的输入,也被强行转换成/分隔的格式,跳过了格式校验。
  2. 日期校验不完整:只判断了日期是否大于31,没有验证日期下限(不能小于1),也没有根据月份判断对应最大天数(比如4、6、9、11月只有30天,二月要考虑闰年)。

修复后的代码

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

    while True:
        date_input = input("Please insert a Date: ").strip()
        try:
            # 区分两种合法格式
            if ',' in date_input:
                # 格式:Month DD, YYYY
                date_parts = date_input.split(',')
                if len(date_parts) != 2:
                    raise ValueError()
                
                month_day_part = date_parts[0].strip().title()
                year = int(date_parts[1].strip())
                
                month_day = month_day_part.split()
                if len(month_day) != 2:
                    raise ValueError()
                
                month_str, day_str = month_day
                if month_str not in MONTHS:
                    raise ValueError()
                month = MONTHS.index(month_str) + 1
                day = int(day_str)

            elif '/' in date_input:
                # 格式:MM/DD/YYYY
                date_parts = date_input.split('/')
                if len(date_parts) != 3:
                    raise ValueError()
                
                month = int(date_parts[0])
                day = int(date_parts[1])
                year = int(date_parts[2])
                
                if not 1 <= month <= 12:
                    raise ValueError()

            else:
                # 既无逗号也无斜杠,格式非法
                raise ValueError()

            # 验证日期合法性(按月份判断最大天数)
            max_days = 31
            if month in [4, 6, 9, 11]:
                max_days = 30
            elif month == 2:
                # 闰年判断规则
                if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
                    max_days = 29
                else:
                    max_days = 28
            
            if not 1 <= day <= max_days:
                raise ValueError()
            
            # 验证年份为4位数(作业隐含要求)
            if len(str(year)) != 4:
                raise ValueError()

            # 输出ISO格式
            print(f"{year}-{month:02}-{day:02}")
            break

        except (ValueError, IndexError):
            # 任何非法情况都重新提示输入
            pass

if __name__ == "__main__":
    main()

修复后的效果

  • October/9/1701:属于混合格式,既不符合带逗号的单词格式,也不符合纯数字斜杠格式,会触发格式校验失败,重新提示输入。
  • September 8 1636:缺少单词格式必需的逗号,触发格式校验失败,重新提示输入。
  • 同时补充了完整的日期合法性校验,比如2月29日仅在闰年有效,4月最多30天等。

内容的提问来源于stack exchange,提问作者Onurb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:02:49