How can I condense this simple if line?

I have a line of code in my program that checks if a number is divisible by several numbers.

However, the way I'm currently using is extremely inefficient and ugly.

Currently it looks like this:

if(x % 1 == 0 and x % 2 == 0 and x % 3 == 0)etc. for several other numbers. I was hoping someone would teach me how I can pull out a long chain andand help me replace it with something that makes more sense, so it would look like this:

if(x % a[1,2,3] == 0)

Is this possible, and if so, can someone help me?

EDIT: x% 1 == 0, x% 2 == 0, etc. This is not a complete equation. I check a lot more than% 1,2, and 3. I'm looking for a solution that can take, say, 1 to 15. That's why I don't use x% 6.

+4
source share
4 answers
if all(x % k == 0 for k in [1, 2, 3]):
    print 'yay'
+15
source
n = 1*2*3
if(x%n == 0):
    #do stuff

Will work for any set of primes.

+3
source

1 to 15, you can use all(x % (k+1) == 0 for k in range(15)). eg:

>>> for x in range(10):
...  if all(x % (k+1) == 0 for k in range(3)): #checks weather x is divisible by 1,2,3
...   print x
... 
0
6
0
source
lcm = LCM of set of number to divide i.e. (1,2,3....)
if(x % lcm == 0)
   //pass
0
source

Source: https://habr.com/ru/post/1532822/


All Articles