[英]time pass algorithm in python
import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question
for i in random.sample(list(questions), 5):
question = questions[i]
if time.time() < current_time+allowed_time:
answer = input("1. soru --> {} : ".format(i))
if answer == question:
correct += 1
elif answer == "":
blank += 1
else:
wrong += 1
print()
print("right answer :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)
请在上方查看我的调查代码。 它在25秒的总时间内随机选择5个问题。 但是,我想为每个问题设置时间选项。 例如,必须在十秒钟内回答问题,否则将自动更改问题。
您能帮上忙吗?
这是进行的步骤(算法):
在for循环内运行一个计数器或计时器,然后对于每次传递的迭代,将时间存储在变量x中,检查x是否小于10。
迭代到下一个问题,即i + 1。
input()
函数-根据其定义- 无限等待输入。 可能没有针对它的跨平台解决方案。
对于*nix
操作系统,您可以执行以下操作:
使用计时器创建另一个线程,该线程将在一段时间后中断主线程 。
您可以为您的输入定义一个函数来实现:
import thread # _thread for Python 3.x
import threading
def timed_input(prompt, timeout=25.):
timer = threading.Timer(timeout, thread.interrupt_main)
answer = ""
try:
timer.start()
answer = input(prompt)
except KeyboardInterrupt:
pass
timer.cancel()
return answer
然后使用它代替代码中的标准input()
函数(当然,也无需使用time
模块进行原始尝试)。
从程序员的角度来看, 最简单 , 最优雅的选择也许就是无限地保留答案时间, 但是如果在给定的时间限制后回答,则将其拒绝 :
start_time = time.time()
answer = input("1. soru --> {} : ". format(i))
if time.time() - start_time > allowed_time:
# code for rejecting the answer
因此,而不是您的for
循环,请使用以下代码( 经过测试的) ,并进行了改进 :
for j, i in enumerate( random.sample(list(questions), 5) ): # Slight change
question = questions[i]
start_time = time.time()
answer = input("{}. soru --> {} : ". format(j + 1, i)) # Sligth change
if time.time() - start_time > allowed_time:
print(" Time-out: You didn't answer quickly enough.")
answer = ""
if answer == question:
correct += 1
elif answer == "":
blank += 1
else:
wrong += 1
并不是说我稍微改变了您的for
陈述和answer = ...
以便打印正确的有序问题 (您的始终为1.
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.