Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: iterate through a list

Tags:

python

loops

list

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?

like image 305
Luis Avatar asked Jan 22 '15 17:01

Luis


People also ask

Can you iterate through a list Python?

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.

How do I iterate over a 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().

How do you iterate through a list without a loop in Python?

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.


2 Answers

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

like image 118
Alex Martelli Avatar answered Sep 22 '22 14:09

Alex Martelli


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...

like image 20
user2782067 Avatar answered Sep 19 '22 14:09

user2782067