You need to enable JavaScript to run this app. Python日期星期计算代码VPL仅过13/16测试 3用例失败求修复
优惠活动
大模型
产品
解决方案
定价
更多

Python日期星期计算代码VPL仅过13/16测试 3用例失败求修复

Python日期转星期代码bug修复方案

问题根因

提交的代码未通过3个测试用例的原因如下:

  • 执行顺序错误:未完成日期合法性校验就提前修改了1月、2月对应的month、year值适配计算公式,导致1月、2月的天数校验规则完全无法匹配,输入1月32、2月32这类异常值不会被拦截。
  • 2月校验逻辑缺失:仅实现了闰年2月的天数校验,未补充平年2月最多28天的校验规则,1900年是平年,输入2月29不会被拦截。
  • 存在冗余代码和缩进错误:month=[1,12]为无效代码,年份校验的while循环开头多了不必要的缩进。

修复方案

调整代码顺序,所有输入校验完成后再修改month、year值适配星期计算逻辑,补充平年2月的天数校验,删除冗余代码修正缩进。修复后的完整代码如下:

year=int(input("Year: "))
while year<1583 or year>9999:
    print("Out of allowed range 1583 to 9999")
    year=int(input("Year: "))
leap_year=year%4==0 and (year%100 !=0 or year%400==0)

month=int(input("Month: "))
while month<1 or month >12:
    print ("Out of allowed range 1 to 12")
    month=int(input("Month: "))

day=int(input("Day: "))
# 先完成所有天数校验
if month in [1,3,5,7,8,10,12]:    
    while day<1 or day> 31:
        print("Out of allowed range 1 to 31")
        day=int(input("Day: "))
elif month in [4,6,9,11]:
    while day<1 or day >30:
        print("Out of allowed range 1 to 30")
        day=int(input("Day: "))
elif month==2:
    if leap_year:
        while day<1 or day>29:
            print("Out of allowed range 1 to 29")
            day=int(input("Day: "))
    else:
        # 补充平年2月校验逻辑
        while day<1 or day>28:
            print("Out of allowed range 1 to 28")
            day=int(input("Day: "))

# 校验全部通过后再调整月年适配公式
if month==1 or month==2:
    month+=12
    year-=1        

weekday = ( day + 13*(month+1)// 5 + year + year// 4- year//100+year// 400)% 7

if weekday==0:
    print("It is a Saturday.")
elif weekday==1:
    print("It is a Sunday.")
elif weekday==2:
    print("It is a Monday.")
elif weekday==3:
    print("It is a Tuesday.")
elif weekday==4:
    print("It is a Wednesday.")
elif weekday==5:
    print("It is a Thursday.")
elif weekday==6:
    print("It is a Friday.")

验证结果

修复后3个未通过的测试用例均会被正常拦截:

  • 1900年2月29:触发平年2月校验,提示Out of allowed range 1 to 28
  • 2018年1月32:触发1月天数校验,提示Out of allowed range 1 to 31
  • 2018年2月32:触发平年2月校验,提示Out of allowed range 1 to 28

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:48:01