import random, re
score = 0
i = 1
while i < 11:
ops = ["-","+","*"]
num1, num2, operation, userans = random.randint(1,4),random.randint(5,12),random.choice(ops),"",
q = (str(num1) + operation + str(num2) + ": ")
while userans == "" or not re.match(r'^[0-9-]*$', userans):
userans = input(q)
if operation == '+':
product = num1+num2
elif operation == '-':
product = num1-num2
elif operation == '*':
product = num1*num2
if str(product) == userans:
print ("you are correct!")
score = score + 1
else:
print("You are incorrect! The correct answer was " + str(product))
print ("Your score is " + str(score))
i=i+1
这是我的代码,但我需要它不那么迟钝。该程序也是随机问题生成器
答案 0 :(得分:2)
试图适应你的问题的精神,并充实说出它不必要的评论(它是),我对你的剧本感到厌烦,所以它总是读到&#39; 20&#39;来自用户(有时是正确的)并且只是构建输出字符串但不打印它们,所以我可以通过timeit
模块运行它。
开始:20,000次在~1.47秒内运行。
from random import choice, randint
使它们成为本地名称以便更快地查找,与re.match
相同,在20,000次运行中提高~0.04秒。 while not userans.isdigit():
,这对于正整数答案来说可能已经足够了,~0.31s
结束:20,000次运行〜0.996秒。
结果:快1/3!万岁!如果我的版本是100%,那么你的版本是150%。如果我的版本难以阅读,那就好了。
from random import randint, choice
from re import match
score = 0
i = 1
ops = ["-","+","*"]
ops2 = {"-":sub,"+":add,"*":mul}
while i < 11:
num1, num2, operation, userans = randint(1,4),randint(5,12),choice(ops),"",
q = (str(num1) + operation + str(num2) + ": ")
product = str(ops2[operation](num1, num2))
while not userans.isdigit():
userans = input(q)
if userans == product:
print("you are correct!")
score = score + 1
else:
print("You are incorrect! The correct answer was " + product)
print("Your score is " + str(score))
i=i+1
但
我们在20,000次运行中说话速度提高0.5秒。每10个问题运行0.000025秒。每个问题/答案快0.0000025秒。
涉及随机数,这几乎是测量噪音。这些微小的变化可能会受到不同版本的Python运行时内部影响很大的影响。
2.5微秒,是吗? Oft quoted figures说人类觉得事情是即时的&#34;大约10-100毫秒。
你的代码已经足够快,不会让它感到迟钝。
如果感觉有些迟钝,可能涉及网络 - 通过SSH或远程桌面在远程计算机上运行代码,或在Web浏览器中通过Internet运行代码。或者它是一个破碎的终端客户端或基于网络的终端,它与基本的文本输入/输出相悖。
相反,为了便于阅读,请稍微修改一下 - 例如从1到小于11的计数作为循环十次的方法。改变&#34; *&#34;到&#34; +&#34;在正则表达式中失去&#34; userans =&#34;&#34;&#34;检查,删除一些str()正在进行,不要称之为&#34;产品&#34;什么时候它可能是一个总和或差异。
from random import randint, choice
import re
score = 0
operations = ["-", "+", "*"]
for turn in range(10):
num1 = randint(1,4)
num2 = randint(5,12)
operation = choice(operations)
q = "{0} {1} {2}: ".format(num1, operation, num2)
userans = ""
while not re.match('^[0-9-]+$', userans):
userans = input(q)
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
result = str(result)
if result == userans:
print ("you are correct!")
score = score + 1
else:
print("You are incorrect! The correct answer was " + product)
print ("Your score is " + str(score))