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?
We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list.
Obtain an iterator to the start of the collection by calling the collection's iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. Within the loop, obtain each element by calling next().
6. Python enumerate() method to iterate a Python list. Python enumerate() function can be used to iterate the list in an optimized manner. The enumerate() function adds a counter to the list or any other iterable and returns it as an enumerate object by the function.
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:-)
Def recadd(lis):
If lis[0] + lis[1] - lis[2]] = lis[3]:
return lis
Else:
recadd(lis[3] + lis[0:2])
recadd(lis[0] + lis[3] + lis[1:2])
recadd(lis[0:1] + lis[3]. + lis[2])
Quick and dirty hack on my mobile, could be elegantly expanded for k numbers, untested but it should work.
Edit: realized this won't work if there is no solution.infinite recursion...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With