Created
April 2, 2012 17:37
-
-
Save diogojc/2285523 to your computer and use it in GitHub Desktop.
Generates every possible combination from a set of discrete variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
def combinations(S): | |
""" | |
Generates every possible combination from a set of discrete variables | |
Arguments | |
--------- | |
S: Cardinality of variable space. When S = [2, 3, 4] variables 1, 2 and | |
3 have 2, 3 and 4 possible events respectively. | |
Returns | |
--------- | |
Generator object yields every possible combination. | |
""" | |
return combinationsAux(S, []) | |
def combinationsAux(S, P): | |
if not S: | |
yield P # We have found a new combination | |
else: | |
for i in xrange(1, S[0] + 1): | |
for perm in combinationsAux(S[1:], P + [i]): # Lets explore more combinations | |
yield perm | |
# Unit tests | |
if __name__ == '__main__': | |
states = [2, 3, 2] | |
# Is the number of combinations correct? | |
assert reduce(lambda a, b: a * b, states) == len(list(combinations(states))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment