How to make this Block of python code short and efficient

后端 未结 11 2482
天命终不由人
天命终不由人 2020-12-15 16:48

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\\         


        
11条回答
  •  萌比男神i
    2020-12-15 17:38

    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.

提交回复
热议问题