我正在尝试创建一个使用随机运算符生成随机算术问题的程序。我可以随机生成“+”和“ - ”,但不能生成“*”或“/”,因为它们有趣的类型。到目前为止,这是我的代码:
from random import randint
try:
score = 0
while 1:
x1 = randint(0, 99)
x2 = randint(0, 99)
x3 = randint(0, 99)
correctAnswer = x1 + x2 + x3
correctAnswer = str(correctAnswer)
print(str(x1) + "+" + str(x2) + "+" + str(x3))
yourAnswer = raw_input("Answer: " )
if yourAnswer == correctAnswer:
print("Correct!")
score += 1
else:
print("Wrong! Ans:" + str(correctAnswer))
except KeyboardInterrupt:
print("Score:" + str(score))
如何更改我的代码以实现这些算术问题的随机运算符生成器?
答案 0 :(得分:0)
看起来您在评论中得到了答案,但我想我可能会尝试鼓励您不要使用eval
,这通常被认为是一种糟糕的做法。
Python可以做的一件好事是你可以实际导入operators作为函数,而不必使用字符。例如
from operator import mul
a = mul(2, 5)
b = 2 * 5
会导致a
和b
都为10
。
将它与减少和一些字符串格式相结合,你的程序可以比eval
字符串更整洁。
from random import randint, choice
from operator import add, sub, mul
score = 0
try:
while True:
x1 = randint(0, 99)
x2 = randint(0, 99)
x3 = randint(0, 99)
operator, operator_symbol = choice([
(add, '+'),
(sub, '-'),
(mul, '*'),
])
correct_answer = reduce(operator, [x1, x2, x3])
print("{x1} {op} {x2} {op} {x3}".format(
x1=x1,
x2=x2,
x3=x3,
op=operator_symbol
))
your_answer = raw_input("Answer: ")
if your_answer == correct_answer:
print("Correct!")
score += 1
else:
print("Wrong! Ans: " + str(correct_answer))
except KeyboardInterrupt:
print("Score:" + str(score))
此代码缺少分歧,因为只是随机生成数字,您将获得0
作为答案的最多次。您可以使用@JohnColeman在其评论中所考虑的因子生成理念。