简体   繁体   中英

Shorten the number of logical checks

Is there a way to shorten the number of checks

    def is_render(self):
        if not hasattr(self, 'p') : return True
        if hasattr(self, 'p') and 'render' not in self.p : return True
        if hasattr(self, 'p') and 'render' in self.p and self.p['render'] != 0 : return True
        return False

ie

if not A : true
elif A and not B : true
elif A and B and not C : true
else false

... even better if I can check simultaneously x != 0 or x is not False

This:

if not A : true
elif A and not B : true
elif A and B and not C : true
else false

is equivalent to:

if A:
    if B:
        if C:
            return False
return True

As demonstrated by the following test...

from itertools import product

def check_1(A, B, C):
    if not A:
        return True
    elif A and not B:
        return True
    elif A and B and not C:
        return True
    else:
        return False

def check_2(A, B, C):
    if A:
        if B:
            if C:
                return False
    return True

for each in product([True, False], repeat=3):
    if check_1(*each) == check_2(*each):
        result = "equivalent"
    else:
        result = "not equivalent"

    print(f"{each}\t-> {result}")

...which returns:

(True, True, True)      -> equivalent
(True, True, False)     -> equivalent
(True, False, True)     -> equivalent
(True, False, False)    -> equivalent
(False, True, True)     -> equivalent
(False, True, False)    -> equivalent
(False, False, True)    -> equivalent
(False, False, False)   -> equivalent

Of course it'd be possible to us an all expression like this...

def check_3(A, B, C):
    return False if all([A, B, C]) else True

...and get the exact same result (I've checked). But I'm guessing you want to only check certain conditions if other conditions have already evaluated as True, for fear of an exception or something - hence the nested ifs.

Not sure if this meets your definition of "shorter", or whether it addresses your original issue - but hope this helps anyhow.

this seem to do it too.. default is True, only explicitly rendering can be turned off

def is_render(self):
    if hasattr(self, 'p') and 'render' in self.p and self.p['render'] == 0 : return False
    return True

thanks for the suggestions

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