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?