Jerry Luke Jerry Luke - 1 month ago 10
Python Question

There has to be a better way

Is there a more idiomatic way to accomplish the following in Python3?

if i%1 == 0 and i%2 == 0 and i%3 == 0 and i%4 == 0 and i%5 == 0 and i%6 == 0 and i%7 == 0 and i%8 == 0 and i%9 == 0 and i%10 == 0 and i%11 == 0 and i%12 == 0 and i%13 == 0 and i%14 == 0 and i%15 == 0 and i%16 == 0 and i%17 == 0 and i%18 == 0 and i%19 == 0 and i%20 == 0:


I'm trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20. I'm not looking for a new solution. I'm looking for a neater way to express what I am doing above.

Answer

Yes use all with range:

if all(i % j == 0 for j in range(1, 21)): # python2 -> xrange(2, 21) 
   # do whatever

If all i % j == 0, it will return True otherwise it will short circuit and return False if there is any remainder for i % j. Also, checking if i % 1 is redundant so you can start at 2.

Or conversly, check if there is not any i % j with a remainder.

if not any(i % j for j in range(2, 21)):

Or if you prefer functional:

if not any(map(i.__mod__, range(2, 21)))
Comments