Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this Block of python code short and efficient

I am total newbie to programming and python. I was solving a problem. I found the solution but it seems like too slow.

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

This is the piece the code to check whether n is divisible by all numbers from 2 to 20 or not.

How I can make it short and efficient.

like image 250
Sanatan Chaudhary Avatar asked Aug 03 '16 11:08

Sanatan Chaudhary


People also ask

How do you make a code block in Python?

To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python.

What do you use to block of code in Python?

Braces {} are used to define a block of code in most programming languages, like C, C++, and Java. But this indentation makes python unique among all programming languages. This indentation highlights the block of code. In Python, indentation is done with whitespace.


1 Answers

There's a trade-off between short and efficient.

The Short way is if all(n % i == 0 for i in range(2, 21)):

The Efficient way is to notice that things like n % 20 == 0 also mean that n % f == 0 where f is any factor of 20. For example, you can drop n % 2 == 0. So you'll end up with fewer comparisons which will run faster. In doing this you'll notice a pattern and you'll notice that the entire statement reduces to if n % 232792560 == 0! But that has now deeply embedded the 20 within it so will be difficult to unpick if you need a different upper limit.

So you see that the efficient way is not so easy to read and maintain. So pick the one best suited to your requirements.

like image 197
Bathsheba Avatar answered Sep 23 '22 11:09

Bathsheba