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

CS50P用餐问题提交超时:本地运行正常但提交报错求助

解决CS50用餐问题提交超时的问题

你的代码存在几个关键问题,导致提交时出现超时错误:

  1. 多余的输出干扰评测系统

    • main函数里的print(a)会输出转换后的时间,这不符合题目要求,评测系统会因为额外输出无法匹配预期结果,进而等待程序退出超时。
    • convert函数里的错误提示打印print("minutes can't be greater than 60")也是多余输出,CS50测试用例均为合法输入,不需要该处理。
    • input函数带提示语"what time is it?",评测系统自动输入时,该提示语会被当作输出的一部分,导致系统判断异常。
  2. 未处理12小时制时间格式
    题目要求convert函数需支持HH:MM和HH:MM AM/PM两种输入格式,你的代码仅处理了前者,遇到带AM/PM的测试用例时会报错,导致程序无法正常退出。

  3. 输出格式不匹配
    你输出的"Lunch time"首字母大写,而题目要求的是小写"lunch time",这会导致评测系统判定输出错误。

修改后的代码

def main():
    time = input()
    converted_time = convert(time)
    if 7 <= converted_time <= 8:
        print("breakfast time")
    elif 12 <= converted_time <= 13:
        print("lunch time")
    elif 18 <= converted_time <= 19:
        print("dinner time")


def convert(time):
    if "AM" in time or "PM" in time:
        time_segment, period = time.split()
        hours, minutes = time_segment.split(":")
        hours = int(hours)
        minutes = int(minutes)
        
        if period == "AM":
            if hours == 12:
                hours = 0
        else:
            if hours != 12:
                hours += 12
    else:
        hours, minutes = time.split(":")
        hours = int(hours)
        minutes = int(minutes)
    
    return hours + minutes / 60


main()

关键修改说明

  • 移除所有多余输出,包括转换后的时间打印、错误提示和输入提示语。
  • 新增12小时制时间处理逻辑,正确转换AM/PM格式的时间。
  • 修正用餐时间的输出格式,确保与题目要求一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:08:25