Python:`choice()`选择相同的选择

Eva*_*olo 0 python

我正在尝试编写一个简单的数学表达式生成器.我遇到的问题是使用从一个范围内选择的随机数表达式,并在每个数字之间插入一个随机运算符.

这是我到目前为止所拥有的:

from random import randint
from random import choice

lower = int(raw_input("Enter a lower integer constraint: "))
higher = int(raw_input("Enter a higher integer constraint: "))

def gen_randoms(lower, higher):
    integers = list()
    for x in xrange(4):
        rand_int = randint(lower, higher)
        integers.append(rand_int)
    return integers

def gen_equations(integers):
    nums = map(str, integers)
    print nums
    operators = ['*', '+', '-']
    equation = 'num op num op num op num'
    equation = equation.replace('op', choice(operators))
    equation = equation.replace('num', choice(nums))
    print equation

nums = gen_randoms(lower, higher)
gen_equations(nums)
Run Code Online (Sandbox Code Playgroud)

这里的问题是输出将重复运算符选择和随机整数选择,因此它给出5 + 5 + 5 + 51 - 1 - 1 - 1代替类似的东西1 + 2 - 6 * 2.如何指示choice生成不同的选择?

Mar*_*ers 5

str.replace()用第二个操作数替换所有出现的第一个操作数.它并没有把第二个参数作为表达,但是.

一次更换一个事件; 该str.replace()方法采用第三个参数来限制进行的替换次数:

while 'op' in equation:
    equation = equation.replace('op', choice(operators), 1)
while 'num' in equation:
    equation = equation.replace('num', choice(nums), 1)
Run Code Online (Sandbox Code Playgroud)

现在choice()通过循环调用每次迭代.

演示:

>>> from random import choice
>>> operators = ['*', '+', '-']
>>> nums = map(str, range(1, 6))
>>> equation = 'num op num op num op num op num'
>>> while 'op' in equation:
...     equation = equation.replace('op', choice(operators), 1)
... 
>>> while 'num' in equation:
...     equation = equation.replace('num', choice(nums), 1)
... 
>>> equation
'5 - 1 * 2 * 4 - 1'
Run Code Online (Sandbox Code Playgroud)