How to make this Block of python code short and efficient

后端 未结 11 2474
天命终不由人
天命终不由人 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条回答
  •  既然无缘
    2020-12-15 17:20

    I don't know if answering your own question is good or not.

    Since I need to check. if a number is divisible by numbers from 1 to 20 or not. So it gonna take long time to check. But if I could make checklist shorter then it will efficient.

    Like, if a number is divisible by 18 then it also should be divisible by 2   3   6 and  9. So based on this I made my checklist:

    if all(n % i == 0 for i in [7,11,13,16,17,18,19,20]):
    
        # some code
    

    And for 14    15 and 12 think like that.

    14 : If a number is divisible by both 2 and 7 it must be divisible by 14.

    15: So in the case of 15 that if a number is divisible by 20 so it also should be divisible by 5 and if a number is divisible by 18 so it also should be divisible by 3 and if a number is divisible by both 3 and 5 then it must be divisible by 15.

    This is more efficient than checking all number and it also ensures that the number is divisible by all number between 1 and 20.

提交回复
热议问题