I´ve a mind challenge riddle that i want to resolve using python.
They give 4 numbers (25, 28, 38, 35) and they want us to place the numbers in ...+...-...=... One possible solution is 25+38-35=28. I´ve tried to, making a list from the numbers, iterate them with some loops and an if:
lst=[25, 28, 38, 35]
for z in lst:
for x in lst:
for c in lst:
for v in lst:
if z+x-c==v:
print z,x,c,v
But when a run the for loops they repeat the numbers, (25+25-25=25) and that don´t work. How can i solve it?
解决方案
As Luis' comment hinted, a good approach is
import itertools
for z, x, c, v in itertools.permutations(lst):
if z+x-c==v:
print z,x,c,v
"flat is better than nested", as import this at an interactive Python prompt will remind you:-)