'How would you write efficient functional code that validates mutual exclusion rules represented as sets?

First of all, this question has nothing to do with concurrency control, and is talking purely about the logical concept of mutual exclusivity.

So say we have mutual exclusion represented as sets of strings, such that some other set cannot have more than one of these strings in it, or else we say it has failed the mutual exclusion validation. For instance:

from functools import reduce

mutually_exclusive_sets = [
    {"a", "b", "c", "d", "e"},
    {"g", "h", "i"},
    {"x", "y", "z"},
]


# function to validate a single of the mutual exclusion rules
def validate_mutex_set(mutex_set, test_set):
    count = 0
    for field in mutex_set:
        if field in test_set:
            count += 1
            if count > 1:
                return False
    return True


# function to validate a set of strings for all rules
def validate_mutex_rules(mutex_sets, test_set):
    return all(validate_mutex_set(mutex_set, test_set) for mutex_set in mutex_sets)


test_set_pass = {"a", "h", "z", "f"}
test_set_fail = {"a", "b", "z", "f"}
print(validate_mutex_rules(mutually_exclusive_sets, test_set_pass))
print(validate_mutex_rules(mutually_exclusive_sets, test_set_fail))

Running it we get

True
False

As expected, but I can't help but feel there is a way you could write this efficiently in a functional style, but my standard tools don't seem to really work here. For instance:

def validate_mutex_set(mutex_set, test_set):
    return reduce(lambda count, field: count + (1 if field in mutex_set else 0), test_set, 0) < 2

This works, but does not short circuit, for large sets of mutual exclusion this is not optimal. And the functions that do short circuit (any() and all()) don't seem to fit here either.

Am I missing something obvious? Is this just an idea that doesn't transfer well to the functional style? It feels like I need a general parameterized version of any() and all(), that short circuits on values of true greater or less than a given number. (although I can't think of a good pythonic name for these)

This optimization isn't extremely important in any capacity, but I was just curious if there was some tool that would let me expand my functional programming toolbox that I'm missing here.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source