Python: `choice()` selecting the same choice -
i attempting write simple math expression generator. problem having achieving expression random numbers selected within range, , inserting random operator between each number.
here's have far:
from random import randint random import choice lower = int(raw_input("enter lower integer constraint: ")) higher = int(raw_input("enter higher integer constraint: ")) def gen_randoms(lower, higher): integers = list() 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 output repeat operator choice , random integer selection, gives 5 + 5 + 5 + 5
or 1 - 1 - 1 - 1
instead of 1 + 2 - 6 * 2
. how instruct choice
generate different selections?
str.replace()
replaces all occurrences of first operand second operand. not treat second argument expression, however.
replace one occurrence @ time; str.replace()
method takes third argument limits how many replacements made:
while 'op' in equation: equation = equation.replace('op', choice(operators), 1) while 'num' in equation: equation = equation.replace('num', choice(nums), 1)
now choice()
called each iteration through loop.
demo:
>>> 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'
Comments
Post a Comment