How to make this Block of python code short and efficient

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

    For variety, the way you could have used a loop for this is

    test = True
    for modulus in range(2, 21):
        if n % modulus != 0:
            test = False
            break
    if test:
        # Do stuff
    

    If you are comfortable with for-else, you can improve the brevity by

    for modulus in range(2, 21):
        if n % modulus != 0:
            break
    else:
        # Do stuff
    

    although that pattern may be unusual enough that you wouldn't want to use it.

    Another option is to write a helper function

    def is_divisible_by_integers_up_to(n, bound):
        for modulus in range(2, bound + 1):
            if n % modulus != 0:
                return False
        return True
    
    if is_divisible_by_integers_up_to(n, 20):
        # Do stuff
    

    However, this particular example is simple enough that doing all with a generator expression as described in the other answers is the best way to go.

提交回复
热议问题