Generation of Combinatorial Objects · Generating Permutations
Lesson 3
Now let's implement the enumeration ourselves. The code will resemble binary sequence enumeration. For binary sequences it was simple: each position could be either zero or one. With permutations it's a bit more complex: at the first position, we can place any of the \(n\) elements; at the second — any of the remaining \((n-1)\); at the third — any of the remaining \((n-2)\); and so on.
def permutations(universe, k):
def helper(perm, k):
if len(perm) == k:
yield perm
else:
for i in universe:
if i not in perm:
yield from helper(perm + [i], k)
yield from helper([], k)
for p in permutations('abc', 2):
print(*p, sep='', end=' ')ab ac ba bc ca cb