Skip to content

Instantly share code, notes, and snippets.

@diogojc
Created April 2, 2012 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diogojc/2285523 to your computer and use it in GitHub Desktop.
Save diogojc/2285523 to your computer and use it in GitHub Desktop.
Generates every possible combination from a set of discrete variables
#!/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