Home > Net >  Write swapped conditions with if-else efficiently (python)
Write swapped conditions with if-else efficiently (python)

Time:11-19

I was trying to code conditions with 2 objects, which their conditions could be swapped. Looks something like:

# pseudo code
if (obj_a meets condition_a and obj_b meets condition_b) or 
   (obj_a meets condition_b and obj_b meets condition_a): return True
else: return False

Edit: The function should return True if all conditions meets different objects in whatever order

But this seems very hard-coded, if I had more objects and more conditions, that's gonna be a bunch of identical lines with swapped conditions. How do I manage to code this efficiently? for example:

# objs are Capitalized, conditions have a trailing tail for easier reading. (pseudo code)
if (A.a_ and B.b_ and C.c_) or
   (A.b_ and B.c_ and C.a_) or
   (A.c_ and B.a_ and C.b_) or
   (A.b_ and B.a_ and C.c_) or
   (A.c_ and B.b_ and C.a_) or
   (A.a_ and B.c_ and C.b_): return True
else: return False

CodePudding user response:

If objects is the sequence of object you wand to apply the conditions to and condition is some function that checks the condition in question, then you can implement this using the builtin any and itertools.permutation as

any(condition(perm) for perm in itertools.permutations(objects))

Using the example from the question, we could have

def condition(a, b, c) -> bool:
    return a.a_ and b.b_ and c.c_

if any(condition(perm) for perm in itertools.permutations([A, B,C ])):
   return True
else: 
   return False

CodePudding user response:

First of all

if condition:
    return True
else:
    return False

is an antipattern. Just use

return condition

or

return bool(condition)

if your condition does not return a boolean.

Now for your question, you could do something like this:

def compute_conditions(objects, conditions):
    perms = permutations(zip(objects, conditions))
    for perm in perms:
        result = True
        for obj, cond in perm:
            if not getattr(obj, cond)():    # Assuming that `a_` etc. are methods
                result = False
                break
        if result:
            return True
    return False


objects = (A, B, C)
conditions = ("a_", "b_", "c_")
if compute_conditions(objects, conditions):
    # Do things
else:
    # Don't do things
  • Related