[英]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.