Because of their demand only nature, generators are ideal for finding the combinations of larger sequences. This code applies a Python generator to find the combinations of the sequence. Since permutations are a special case of combinations for all the items in a sequence, I have expanded the result to give the permutations of a string.

```
# using a combinations-generator for larger permutations
# tested with Python24 by vegaseat 10sep2006
def xcombinations(items, n):
if n == 0:
yield []
else:
for i in xrange(len(items)):
for cc in xcombinations(items[:i] + items[i+1:], n-1):
yield [items[i]] + cc
def xpermutations(items):
"""permutations are just a special case of combinations"""
return xcombinations(items, len(items))
# test the above functions ...
if __name__=="__main__":
word = 'workmen'
charList = list(word) # ['w', 'o', 'r', 'k', 'm', 'e', 'n']
print "Permutations of '%s' -->" % word
for pm in xpermutations(charList):
# reform the word
print ''.join(pm)
"""
Permutations of 'workmen' -->
workmen
workmne
workemn
workenm
worknme
worknem
wormken
wormkne
wormekn
wormenk
wormnke
...
"""
```

About the Author

Scientist