Skip to content

Instantly share code, notes, and snippets.

@liang456
Created October 29, 2012 20:31
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 liang456/3976335 to your computer and use it in GitHub Desktop.
Save liang456/3976335 to your computer and use it in GitHub Desktop.
Permutation and Composition Algorithm using Iterator in Python
def PermutationEnumerator(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[:i] + items[i+1:]
for p in PermutationEnumerator(rest, n-1):
yield v + p
def CombinationEnumerator(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[i+1:]
for c in CombinationEnumerator(rest, n-1):
yield v + c
if __name__ == "__main__" :
items = [ 'a', 'b', 'c','d','e']
for selection in range(1, len(items)) :
enum = CombinationEnumerator(items, selection)
for i in enum :
print i
print items
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment