简体   繁体   中英

Fastest way to check for multiple conditions

I am looking to check for 3 conditions, any of which triggers a continue.

The 2 ways I am looking at are 1) if with multiple conditions 2) if and elif

def conditions_1(a,b,c):
    numbers = []
    min_no = min(a,b,c)
    max_no = max(a,b,c)
    for no in range(min_no,max_no+1):
        if no == 0 :
            continue
        elif no + min_no == 0:
            continue
        elif math.gcd(min_no, no)> 1:
            continue
        else:
            numbers.append(no)
    return(numbers)


def conditions_2(a,b,c):
    numbers = []
    min_no = min(a,b,c)
    max_no = max(a,b,c)
    for no in range(min_no,max_no+1):
        if no == 0 or no + min_no == 0 or math.gcd(min_no, no)> 1:
            continue
        else:
            numbers.append(no)
    return(numbers)

for _ in range(10):
    t0 = time.time()
    conditions_1(-5000, 10000, 4)
    t1 = time.time()
    conditions_2(-5000, 10000, 4)
    t2 = time.time()
    if t2-t1 > t1-t0:
        print('2nd')
    else:
        print('1st')

May I know if there is a difference in both ways?

Thanks to the fact that or has short-circuit evaluation (ie, it evaluates the list of conditions left to right and stops at the first True), the execution pattern is the same between your two variants (minus the fact that in the if/elif case you may have multiple jumps when testing each condition).

Coding-style-wise, the second is of course a lot better (no repetition of continue , clearer intent of the if/else block) and should be the way you structure your code.

Side note: Remember that if an expression gets too long, you can put it in parentheses and break it over several lines:

if (some_very_lengthy_condition_1 == my_very_lengthy_name_1 or
    some_very_lengthy_condition_2 == my_very_lengthy_name_2 or
    some_very_lengthy_condition_3 == my_very_lengthy_name_3 ):
  pass # do something

As Gábor noted in the comments, in python you also have the any and all operators, which apply to iterables. any(iterable) is equivalent to or ing all values in the iterable, while all(iterable) is equivalent to and ing them. Short-circuit logic applies here as well, so that only the minimal number of values in iterable are evaluated when computing the expression result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM