vampiire
vampiire

Reputation: 1220

how to shorten this conditional statement (checking if number is divisible by all values from 1-10) python

How can I shorted this conditional statement in Python?

if x % 1 == 0 and x % 2 == 0 and x % 3 == 0 and x % 4 == 0 and x % 5 == 0 
and x % 6 == 0 and x % 7 == 0 
and x % 8 == 0 and x % 9 == 0 and x % 10 == 0:

I have tried:

for x in range(some range):
    for y in range(1,11):
        if x % y == 0:
            do something

However this just checked if all the numbers in x were evenly divisible by 1, 2, 3 etc separately in each loop. I want it to be checked altogether.

Upvotes: 0

Views: 95

Answers (2)

Steven Rumbalski
Steven Rumbalski

Reputation: 45552

Use all with a generator expression:

all(x%n == 0 for n in range(1, 11))

Full example:

test_numbers = (37, 300, 2520, 5041, 17640)
for x in test_numbers:
    if all(x%n == 0 for n in range(1, 11)):
        print('{} is disible by all integers 1 to 10.'.format(x))

Result:

2520 is disible by all integers 1 to 10.
17640 is disible by all integers 1 to 10.

Note that all is efficient because it stops evaluation once a False value is encountered.

Upvotes: 1

elzell
elzell

Reputation: 2306

You could run a for loop to check if the condition is not satisfied for one of the y. The else clause is only executed when no break happened during the for loop.

for x in range(some range):
    for y in range(1,11):
        if x % y != 0:
            break
    else:
        do_something

Edit: Further explanation (as given in the comments)

As soon as for one y x % y is different from 0, the inner for loop is left and the next number x is examined. The else of the inner for loop is only executed after the whole inner for loop has been run through without any break, so when all y satisfy the condition x % y == 0.

Upvotes: 1

Related Questions