Skip to content

Instantly share code, notes, and snippets.

@cansadadeserfeliz
Last active August 29, 2015 13:59
Show Gist options
  • Save cansadadeserfeliz/10992283 to your computer and use it in GitHub Desktop.
Save cansadadeserfeliz/10992283 to your computer and use it in GitHub Desktop.
Permutations of an array in Python
def swap(a, i, j):
t = a[i]
a[i] = a[j]
a[j] = t
def permutations(a, i, n):
if i == n:
print a
else:
for j in range(i, n):
swap(a, i, j)
permutations(a, i + 1, n)
swap(a, i, j)
a = [1, 2, 3]
permutations(a, 0, len(a))
# Output:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
# pic: http://d2o58evtke57tz.cloudfront.net/wp-content/uploads/NewPermutation.gif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment