How to make this Block of python code short and efficient

后端 未结 11 2470
天命终不由人
天命终不由人 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:38

    I'm a very light python user myself, and I didn't know about all. Those solutions are pretty cool (and probably more efficient than the one I'm about to post). But just if you want to see another way to do it, here is another option:

    def IsDivUpTo20(n):
       for i in range(2, 21):
          if n % i != 0:
             return False
       return True
    

    And call it like so

    if IsDivUpTo20(50):
       #what to do if it is divisible
    else:
       #what to do if it isn't
    #for the example of 50, it'll be false and jump to the else part, but you can put any number of variable in there
    

    Functionally it is working pretty much the same way 'all' is, but if you aren't used to the fancy syntax and built-ins this one is a bit more intuitive.

    *Note: I use Python 3, not Python 2.7 as the question is tagged. I'm pretty sure this works in that version but if not, someone please correct me.

提交回复
热议问题