[英]How can I make this code shorter in python? (it runs really slow)
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
这是我拥有的代码,但我需要它不那么滞后。 该程序也是一个随机问题生成器
试图符合你的问题的精神,并充实评论说它是不必要的(它是),我削弱了你的脚本,所以它总是从用户那里读取“20”(有时是正确的)并且只是构建输出字符串但是不打印它们,所以我可以通过timeit
模块运行它。
开始:约 1.47 秒内运行 20,000 次。
from random import choice, randint
使它们成为本地名称以加快查找速度,与re.match
相同,在 20,000 次运行中改进了 ~0.04 秒。while not userans.isdigit():
,这对于正整数答案来说可能已经足够了,~0.31s
完成:约 0.996 秒内运行 20,000 次。
结果:快 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 微秒,是吗? 经常引用的数字说,人类感觉事物在大约 10-100 毫秒内是“即时的”。
你的代码已经足够快了,不会让它感觉滞后。
如果感觉滞后,则可能是涉及网络 - 通过 SSH 或远程桌面在远程计算机上运行代码,或者在 Web 浏览器中通过 Internet 运行代码。 或者它是一个损坏的终端客户端或基于 Web 的终端,它在基本文本输入/输出方面遇到了困难。
取而代之的是,稍微修复它以提高可读性 - 就像从 1 数到小于 11 作为循环十次的方式。 将正则表达式中的“*”更改为“+”并丢失“userans =“””检查,去掉一些正在进行的 str() ,当它可能是一个总和或一个时不要称它为“产品”区别。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.