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.
This one-liner will get all divisible combinations of the elements in iterable
j
: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: