Skip to content

Instantly share code, notes, and snippets.

@gcr
Created April 12, 2009 23:55
Show Gist options
  • Select an option

  • Save gcr/94177 to your computer and use it in GitHub Desktop.

Select an option

Save gcr/94177 to your computer and use it in GitHub Desktop.
def ordered_permutations(words=[]):
"""
Retrun a generator which generates permutations of words chosen from each
set in words.
Example:
>>> begin_letters = ['A', 'B', 'C']
>>> words = [['Albuquerque', 'Animal'], ['Bacon', 'British'],
... ['Cheese', 'Cat'], ['Egg Nog']]
>>> for set_ in ordered_permutations(begin_letters, words):
... print set_
...
('Albuquerque', 'Bacon', 'Cheese')
('Albuquerque', 'Bacon', 'Cat')
('Albuquerque', 'British', 'Cheese')
('Albuquerque', 'British', 'Cat')
('Animal', 'Bacon', 'Cheese')
('Animal', 'Bacon', 'Cat')
('Animal', 'British', 'Cheese')
('Animal', 'British', 'Cat')
"""
return eval('((%s) %s)' % (
','.join(['x%s' % x for x in xrange(len(words))]),
' '.join(['for x%s in words[%s]' %
(x, x) for x in xrange(len(words))]
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment