9

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?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Luis
  • 95
  • 4
  • 11
    Look into itertools.permutations – user2097159 Jan 22 '15 at 17:42
  • Quite aside from the best way to look at all permutations in Python, consider (by adding `c` to both sides of the equation) that you're looking for any two values from the four, that together add up to half the sum. So you don't actually need all 24 permutations, you could consider just 6 partitions: the first 6 values from `itertools.permutations(lst,2)`. And if the values are integers and the sum is odd then forget about it :-) – Steve Jessop Jan 22 '15 at 18:13

2 Answers2

9

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:-)

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
1
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...

user2782067
  • 382
  • 4
  • 19