Python 随机算子发生器

Python 随机算子发生器,python,python-2.7,operators,Python,Python 2.7,Operators,我正在尝试创建一个程序,用随机运算符生成随机算术问题。我可以随机生成“+”和“-”,但不能生成“*”或“/”,因为它们的类型很有趣。以下是我目前的代码: from random import randint try: score = 0 while 1: x1 = randint(0, 99) x2 = randint(0, 99) x3 = randint(0, 99) correctAnswer = x1 +

我正在尝试创建一个程序,用随机运算符生成随机算术问题。我可以随机生成“+”和“-”,但不能生成“*”或“/”,因为它们的类型很有趣。以下是我目前的代码:

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))

我该如何更改代码以实现这些算术问题的随机运算符生成器?

看起来您在评论中得到了答案,但我想我可能会鼓励您不要使用
eval
,这通常被认为是一种糟糕的做法

Python可以做的一件伟大的事情是,您实际上可以作为函数导入,而不必使用字符。比如说

from operator import mul
a = mul(2, 5)
b = 2 * 5
将导致
a
b
均为
10

再加上精简和一些字符串格式,你的程序可以比
eval
ing字符串更整洁

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在他们的评论中提出的因子生成思想。

这还不是很清楚。在上面的代码中,什么会阻止您将
+
替换为
*
?对于商,如果希望最终结果为整数,可以从随机答案开始,然后反向计算。换句话说,如果你想
a/b=c
选择random
c
b
,然后计算有效的
a
。我想你可以用随机运算符字符生成表达式字符串,然后调用eval()来得到正确的答案。我想要的是随机运算符,而不是永久乘数。我希望所有问题都有相同的机会包含+、-、*、或/。然后以相同的机会选择它们——根据您的全局选择有条件地调用上述代码(针对不同运算符进行适当修改)。您还没有解释
*
的“有趣类型”以何种方式阻止您使用
*
您所说的您知道如何使用
+
-
谢谢dsboger,您的回答是正确的。