Dev5
Dev5

Reputation: 459

Python check through two lists

I am relatively new to python and I came across a problem given below:

Given two lists a and b and an integer n, Check if
a) All elements of a is a factor of n
b) n is a factor of all elements of b

My code doesn't seem to be correct. Can someone please point out the mistake here.

return n if n%x==0 for x in a and y%n==0 for y in b

Any help is appreciated

Upvotes: 0

Views: 65

Answers (1)

superb rain
superb rain

Reputation: 5521

Obvious one (you were missing all(...)):

all(n % x == 0 for x in a) and all(y % n == 0 for y in b)

Fun one:

0 == n % reduce(lcm, a) == reduce(gcd, b) % n

Requires Python 3.9, though.

Test code:

from itertools import product
from math import gcd, lcm
from functools import reduce

R = range(1, 11)
true = false = 0
for n in R:
    for a in product(R, repeat=3):
        for b in product(R, repeat=3):
            expect = all(n % x == 0 for x in a) and all(y % n == 0 for y in b)
            result = 0 == n % reduce(lcm, a) == reduce(gcd, b) % n
            assert result == expect
            true += expect
            false += not expect
print(true, false)

=> No failures, same 2,723 true results and 9,997,277 false results.

Upvotes: 1

Related Questions