Python for loop inside for loop/

249 views Asked by At

I am trying to find two numbers in a list which are divisible by each other. I have managed to do this by placing two for loops that loop over the same list to compare numbers until a pair is found.

My Question:

Is it possible to easily compress this code to one or two lines using a conditional statement?

def FindDivisible(j):
    for i in j:
        for m in j:
            if int(i) % int(m) == 0 and int(i) != int(m):
                return([int(i),int(m)])

I do understand that this would not be very pythonic at all. I do however want to know if it is possible and what would be a good way for going about this.

4

There are 4 answers

3
John1024 On BEST ANSWER

This one-liner will get all divisible combinations of the elements in iterable j:

[([int(i),int(m)]) for m in j for i in j if int(i) % int(m) == 0 and int(i) != int(m)]

The above is just your code translated into a list comprehension. One difference is that this will find all combinations while your original looping code will return just the first successful combination. If you want to exit after the first combination, then the explicit looping is the right choice.

For example:

>>> j=range(2,5)
>>> [([int(i),int(m)]) for m in j for i in j if int(i) % int(m) == 0 and int(i) != int(m)]
[[4, 2]]
0
Mr Singh On

You can probably use itertools.product

http://docs.python.org/library/itertools.html#itertools.product

Example as

for var1, var2 in itertools.product(xrange(min1, max1, step1), xrange(min2, max2, step2)):
    # stuff
0
Espoir Murhabazi On

let use itertool combinaison and filter

in 2 lines :

from itertools import combinations
alist =[(x,y) if  (x%y==0 or y%x==0 and x!=y ) else None for x,y in combinations(l, 2)]
L = list(filter(None, alist))
0
chepner On

Use itertools.product. Note that it is simpler to map int over the original input list once, rather than constantly converting individual elements.

from itertools import product
def find_divisible(j):
    return [(i, m) for (i, m) in product(map(int, j), repeat=2) 
             if i % m == 0 and i != m]