Skip to content

Instantly share code, notes, and snippets.

@gsamokovarov
Created June 13, 2013 15:09
Show Gist options
  • Save gsamokovarov/5774466 to your computer and use it in GitHub Desktop.
Save gsamokovarov/5774466 to your computer and use it in GitHub Desktop.
Iterative permutation implementation in Python.
def permute(sequence, index=0):
length = len(sequence)
if index > length:
raise StopIteration
if index == length:
yield sequence
else:
for i in range(index, length):
sequence[i], sequence[index] = sequence[index], sequence[i]
for permutation in permute(sequence, index + 1):
yield permutation
sequence[index], sequence[i] = sequence[i], sequence[index]
for permutation in permute([1, 2, 3]):
print permutation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment