How to make this Block of python code short and efficient

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)