Cookie
Cookie

Reputation: 257

Write swapped conditions with if-else efficiently (python)

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

Upvotes: 3

Views: 79

Answers (1)

Brian61354270
Brian61354270

Reputation: 14433

If objects is the sequence of objects you want 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.permutations as

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

Using the example from the question, we could have

import itertools

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

objects = [A, B, C]

if any(condition(*perm) for perm in itertools.permutations(objects)):
   # Condition passed for some permutation.
else: 
   # Condition did not pass for any permutation.

Upvotes: 2

Related Questions