-
-
Save canwe/31da75382e72d01aa9b9f4c0e8272928 to your computer and use it in GitHub Desktop.
Iterative permutation implementation in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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