Skip to content

Instantly share code, notes, and snippets.

@pyrocat101
Created November 18, 2013 01:38
Show Gist options
  • Save pyrocat101/7521023 to your computer and use it in GitHub Desktop.
Save pyrocat101/7521023 to your computer and use it in GitHub Desktop.
Recursive Permutation in Python
def permutation(xs):
if len(xs) == 1:
return [xs]
ret = []
for x in xs:
for y in permutation(filter(lambda a: a != x, xs)):
ret.append([x] + y)
return ret
def perm(xs):
if len(xs) == 1:
return [xs]
else:
return [([x] + y) for x in xs for y in perm(filter(lambda a: a != x, xs))]
print perm([1,2,3, 4])
print permutation([1,2,3,4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment