Reputation:
if I have two lists:
e = [3,1,5,8]
, w = [1,2,4]
and I want to go in and check which element of e is evenly divisible by every element of w, how do I do this in a list comprehension?
so using my two lists, 8
should be returned since 8 % each i in w
will give a zero.
in terms of a for loop I'm thinking of something like:
for i in e:
for j in w:
if i % j == 0:
print i
but even that is incorrect!
Upvotes: 3
Views: 184
Reputation: 414139
To check which element of e
is evenly divisible by every element of w
:
#!/usr/bin/env python
import fractions
import functools
e = [3,1,5,8]; w = [1,2,4]
lcm = functools.reduce(lambda a,b: a*b // fractions.gcd(a, b), w)
result = [i for i in e if i % lcm == 0]
# -> [8]
This is linear algorithm (if numbers are limited) unlike the nested list comprehension that is quadratic algorithm e.g., if e
, w
were to contain a million numbers each then the linear algorithm would require around a million operations that should be fast even on modest device, at the same time the quadratic algorithm would take ~1e12 (a number with 12 zeros) operations that may take a while.
In general, if you see:
L = []
for i in e:
for j in w:
if i % j == 0:
L.append(i)
then it is equivalent to:
L = [i for i in e for j in w if i % j == 0]
i.e., all you need is to remove colons and add brackets -- the order is exactly the same.
If you need to figure out the correct syntax for a list comprehension then it means that you should probably leave the code as the explicit nested loops.
Upvotes: 1
Reputation: 257
If a number is evenly divisible by every element in a list of numbers then it also has to be evenly divisible with the product of all the numbers in the list.
e = [3,1,5,8, 16, 32]
w = [1,2,4]
product = reduce(lambda a,b: a*b, w)
answer = [i for i in e if i % product == 0]
# print answer -> [8, 16, 32]
Upvotes: 0