2013-08-19 69 views
0

我正在嘗試編寫一個簡單的數學表達式生成器。我遇到的問題是使用從一個範圍內選擇的隨機數來實現表達式,並在每個數之間插入一個隨機運算符。Python:`choice()`選擇相同的選擇

這是我到目前爲止有:

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) 

這裏的問題是輸出將重複運營商選擇和隨機整數選擇,所以它給5 + 5 + 5 + 51 - 1 - 1 - 1,而不是像1 + 2 - 6 * 2。我如何指示choice生成不同的選擇?

回答

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' 
0

此行調用choice只有一次:

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

它取代的'num'每個實例與傳遞的第二個參數的一個值。

這是預期的。

替換字符串中值的正確方法是使用format%運算符。請參閱:http://docs.python.org/2/library/string.html

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

+2

爲什麼downvote? – NPE

+0

@NPE我也很想知道。 – Marcin

+1

建議的「正確方法」不能幫助OP解決他的問題。 –

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,則會出現錯誤,然後會出現替換...