Created
October 29, 2012 20:31
-
-
Save liang456/3976335 to your computer and use it in GitHub Desktop.
Permutation and Composition Algorithm using Iterator in Python
This file contains 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
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