Permutations and combinations are often required in algorithms that do a complete search of the solution space. They are typically rather large so it's best not to compute them entirely but better to lazily generate them. This recipe uses Python 2.2 generators to create appropriate generator objects, that can be use for example as ranges in for loops.
Python, 62 lines
This recipe provides both combinations and permutations and lazily generates them. You can do arbitrary calculations on the permutation/combination items not just print them.
If you require the complete list of permutations, just use the built-in list() operator. Note that the resulting list can be huge.
All x-generators defined here yield sequences with elements from the original sequence. Their difference is in which elements they take:
xpermutations takes all elements from the sequence, order matters.
xcombinations takes n distinct elements from the sequence, order matters.
xuniqueCombinations takes n distinct elements from the sequence, order is irrelevant.
xselections takes n elements (not necessarily distinct) from the sequence, order matters.
Note that 'distinct' means "different elements in the orginal sequence" and not "different value", i.e.
[['a', 'a'], ['a', 'b'], ['a', 'b'], ['a', 'b'], ['a', 'b'], ['b', 'b']]
If your sequence has only items with unique values, you won't notice the difference (no pun intended).