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

CS50P作业Seasons of Love:年龄分钟数计算测试未通过,是否需处理闰年?

问题分析与解决方案

核心问题

你的代码使用date.today()获取真实的当前日期,但CS50的测试用例采用预设的固定日期进行验证。比如测试用例中假设“今天”是你输入生日的一年后(如输入2022-01-01,测试环境的“今天”是2023-01-01),此时天数差为365,计算得525600分钟;但你的本地环境中真实日期可能已超过一年,导致天数差更大,结果不符合测试预期。

解决方法

给validate函数添加一个可选的today参数,默认使用真实当前日期,测试时可传入预设日期对齐测试环境:

from datetime import date
import sys
import inflect

p = inflect.engine()

def main():
    birth_date = input("Date of birth: ")
    print(validate(birth_date))

def validate(d, today=None):
    if today is None:
        today = date.today()
    try:
        birth = date.fromisoformat(d)
    except ValueError:
        sys.exit("Invalid Format")
    
    # 确保生日不晚于当前日期
    if birth > today:
        sys.exit("Birth date cannot be in the future")
    
    difference = today - birth  # 直接用减法运算符,无需operator.__sub__
    total_minutes = difference.days * 24 * 60
    output = p.number_to_words(total_minutes)
    return f"{output.capitalize()} minutes"

if __name__ == "__main__":
    main()

关于闰年的疑问

不需要手动编写闰年检查逻辑。datetime.date的减法运算会自动处理两个日期之间的准确天数,包括闰年的2月29日等特殊情况,直接使用today - birth即可得到正确的天数差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 13:27:05