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

《疯狂一分钟》:如何让循环在时间限制到达时自动退出?

《疯狂一分钟》答题程序超时退出问题修复

问题根源

  1. 外层循环逻辑混乱:原代码同时嵌套while和for循环,for循环会强制遍历完所有题目,完全无视时间限制判断。
  2. 输入阻塞导致超时检测失效:input()是阻塞式函数,用户不输入时程序会一直停在此处,无法触发时间检查逻辑。

修复后的代码

import random
import time
import signal

# 自定义超时异常
class TimeoutException(Exception):
    pass

# 超时处理函数
def timeout_handler(signum, frame):
    raise TimeoutException("Time's up!")

OPERATORS = ["+", "-", "*"]
MIN_OPERAND = 3
MAX_OPERAND = 9
TOTAL_PROBLEMS = 5
LIMIT_TIME = 5  # 测试用的5秒限时

def generateProblem():
    left = random.randint(MIN_OPERAND, MAX_OPERAND)
    right = random.randint(MIN_OPERAND, MAX_OPERAND)
    operator = random.choice(OPERATORS)

    expression = f"{left} {operator} {right}"
    answer = eval(expression)
    return expression, answer

incorrectAnswer = 0
input("Press enter to start!")
print("---------------------\n")

startTime = time.time()
completed_problems = 0

# 设置信号处理器,用于检测超时
signal.signal(signal.SIGALRM, timeout_handler)

try:
    while completed_problems < TOTAL_PROBLEMS:
        # 计算剩余时间,判断是否已超时
        elapsed_time = time.time() - startTime
        remaining_time = LIMIT_TIME - elapsed_time
        if remaining_time <= 0:
            raise TimeoutException("Time's up!")
        
        # 设置超时闹钟,避免设置负数超时时间
        signal.alarm(max(1, int(remaining_time)))
        
        expression, answer = generateProblem()
        try:
            userInput = input(f"Problem #{completed_problems + 1}: {expression} = ")
            # 输入成功,关闭闹钟
            signal.alarm(0)
            
            if userInput == str(answer):
                completed_problems += 1
            else:
                incorrectAnswer += 1
                print("Wrong answer! Try again.")
        except TimeoutException:
            # 输入超时,直接终止程序
            print("\nTime's up! You didn't answer in time.")
            raise
except TimeoutException:
    print("\n---------------------\n")
    endTime = time.time()
    totalTime = round(endTime - startTime, 2)
    finalTime = totalTime + incorrectAnswer
    print(f"You completed {completed_problems} problems in {totalTime} seconds with {incorrectAnswer} incorrect answers! Your final time is {finalTime}")

关键改动说明

  • 新增自定义超时异常和信号处理函数,实现输入超时的强制终止逻辑。
  • 用单个while循环同时控制已完成题目数和剩余时间,替代原有的混乱嵌套循环。
  • 每次等待用户输入前,根据剩余时间设置闹钟,超时直接触发异常并结束程序。
  • 用户输入成功后立即关闭闹钟,避免误触发超时判定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:55:19