I came across a fun math problem yesterday and have it solved, but with the code I wrote, I had to do a keyboard interrupt or it would run forever, lol. So I changed it to have an end condition, but now it only prints 1 solution and stops.
The problem goes like this: “You have the numbers 123456789, in that order. Between each number, you must insert either nothing, a plus sign, or a multiplication sign, so that the resulting expression equals 2002. Write a program that prints all solutions. (There are two.)”
import random
def try1(param):
global solved
opers = ['+', '*', '']
hotpotato = ('%s'.join(param) % (random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
)
)
if eval(hotpotato) == 2002:
solved += 1
print "Solution:", hotpotato, "= 2002 :-)"
else:
pass
solved = 0
while solved == 0:
try1('123456789')
This code prints the first solution it encounters and stops. Can anyone tell me how to get it to print both solutions before it stops?
Store your solutions in a set:
Each time a solution is found, update the set:
Sets are nice because there don’t store duplicates:
So just loop until the set’s size is greater than one:
Also, you can shorten this code:
To this: