Python时间限制

新手上路,请多包涵

我有一项家庭作业要做,我真的需要一个解决方案。从昨天开始我一直在尝试这样做,但我不知道怎么做。

程序必须生成并打印一个字母或数字,然后用户必须尽快键入它并按 ENTER。 30秒后游戏结束。

好吧,我不知道如何给游戏设置时间限制。我正在通过 stackoverflow 进行搜索,但没有找到任何有用的信息。请帮我。

**这是我到目前为止所做的。我尝试了 SYSS.STDER 的答案中的代码,但它不太有效,因为当 30 秒结束时,游戏也应该结束,但是在这段代码中,当我输入最后一个字符时游戏结束了。

循环不会停止,直到它完成并且我们发现我们已经超过了最后期限。任务需要在时间结束后立即中断。

 max_time =30
start_time = time.time()  # remember when we started
while (time.time() - start_time) < max_time:

    response = "a"      # the variable that will hold the user's response
    c = "b"             #the variable that will hold the character the user should type
    score = 0
    number = 0

    c = random.choice(string.ascii_lowercase + string.digits)
    print(c)
    number = number + 1

    response = input("Type a letter or a number: ") #get the user's response

    if response == c and (time.time() - start_time) < max_time:
         # if the response from the previous loop matches the character
         # from the previous loop, increase the score.
         score = score + 1

原文由 Miki 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 666
2 个回答

这是我的方法:

 import string
import random
import time

response = "a"              # the variable that will hold the user's response
c = "b"                     #the variable that will hold the character the user should type
score = 0                   #the variable that will hold the user's score
start = time.time()         #the variable that holds the starting time
elapsed = 0                 #the variable that holds the number of seconds elapsed.
while elapsed < 30:         #while less than 30 seconds have elapsed

    if response == c:       #if the response from the previous loop matches the character
        score += 1          #from the previous loop, increase the score.

    #c is a random character
    c = random.choice(string.ascii_lowercase + string.digits)
    print(c)

    response = input("Type a letter or a number: ") #get the user's response

    elapsed = time.time() - start #update the time elapsed

原文由 bigblind 发布,翻译遵循 CC BY-SA 3.0 许可协议

超过时间限制时退出质数函数的示例程序。

导入数学

从时间导入时间

开始时间 = 时间() 最大时间 = 2

定义素数(n):

     for i in range(2, int(math.sqrt(n))):
        if(time() - start_time) > max_time:
            return "TLE"
        if n % i == 0:
            return False
    return True

打印(质数(3900000076541747077))

原文由 Sri436 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题