0

I am attempting to write a simple math expression generator. The problem I am having is achieving an expression with random numbers selected from within a range, and inserting a random operator between each number.

Here's what I have so far:

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)

The problem here is the output will repeat the operator choice and random integer selection, so it gives 5 + 5 + 5 + 5 or 1 - 1 - 1 - 1 instead of something like 1 + 2 - 6 * 2. How do I instruct choice to generate different selections?

4

3 回答 3

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)

现在,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'
于 2013-08-19T18:42:44.790 回答
4

我会去使用替换dict并用它来替换每个“单词”:

import random

replacements = {
    'op': ['*', '+', '-'],
    'num': map(str, range(1, 6))
}

equation = 'num op num op num op num op num'
res = ' '.join(random.choice(replacements[word]) for word in equation.split())
# 1 + 3 * 5 * 2 + 2

然后,您可以对此进行概括,以便每个单词执行不同的操作,因此选择一个随机运算符,但保持数字顺序...:

replacements = {
    'op': lambda: random.choice(['*', '+', '-']),
    'num': lambda n=iter(map(str, range(1, 6))): next(n)
}

equation = 'num op num op num op num op num'
res = ' '.join(replacements[word]() for word in equation.split())
# 1 + 2 + 3 - 4 * 5

请注意,如果字符串中存在更多的 ',这将引发错误num,然后在替换中......

于 2013-08-19T18:58:42.653 回答
0

此行仅调用choice一次:

equation = equation.replace('num', choice(nums))

它将每个实例替换为'num'您作为第二个参数传递的一个值。

这正如预期的那样。

替换字符串中的值的正确方法是使用format%运算符。请参阅:http ://docs.python.org/2/library/string.html

或者,您可以迭代地构建字符串。

于 2013-08-19T18:40:24.610 回答