Skip to content

Instantly share code, notes, and snippets.

@xguse
Created July 23, 2013 00:50
Show Gist options
  • Save xguse/6058998 to your computer and use it in GitHub Desktop.
Save xguse/6058998 to your computer and use it in GitHub Desktop.
Generators for calculating a) the permutations of a sequence and b) the combinations and selections of a number of elements from a sequence. Uses Python 2.2 generators. Similar solutions found also in comp.lang.python Keywords: generator, combination, permutation, selection See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962
#!/usr/bin/env python
__version__ = "1.0"
"""xpermutations.py
Generators for calculating a) the permutations of a sequence and
b) the combinations and selections of a number of elements from a
sequence. Uses Python 2.2 generators.
Similar solutions found also in comp.lang.python
Keywords: generator, combination, permutation, selection
See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105962
See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66463
See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66465
"""
#from __future__ import generators
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 xuniqueCombinations(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for cc in xuniqueCombinations(items[i+1:],n-1):
yield [items[i]]+cc
def xselections(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for ss in xselections(items, n-1):
yield [items[i]]+ss
def xpermutations(items):
return xcombinations(items, len(items))
#if __name__=="__main__":
#print "Permutations of 'love'"
#for p in xpermutations(['l','o','v','e']): print ''.join(p)
#print
#print "Combinations of 2 letters from 'love'"
#for c in xcombinations(['l','o','v','e'],2): print ''.join(c)
#print
#print "Unique Combinations of 2 letters from 'love'"
#for uc in xuniqueCombinations(['l','o','v','e'],2): print ''.join(uc)
#print
#print "Selections of 2 letters from 'love'"
#for s in xselections(['l','o','v','e'],2): print ''.join(s)
#print
#print map(''.join, list(xpermutations('done')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment