Skip to content

Instantly share code, notes, and snippets.

@thibthibaut
Created August 21, 2017 12:40
Show Gist options
  • Save thibthibaut/267d53cf930421a093a86399bf733c1c to your computer and use it in GitHub Desktop.
Save thibthibaut/267d53cf930421a093a86399bf733c1c to your computer and use it in GitHub Desktop.
# Permutation function in python
# Computes all possible permutations of elements in a list
def permutations(lst):
perms = []
if len(lst) == 2: #This is the stop condition
perms.append(lst)
permuted = lst[0:2] # We need to make a copy
permuted[0], permuted[1] = permuted[1], permuted[0]
perms.append(permuted)
return perms
for index, item in enumerate(lst):
sublist = lst[:index] + lst[index+1 :]
child_perms = permutations(sublist)
for p in child_perms:
p.insert(0, item)
perms.append(p)
return perms
# factorial
def fact(i):
if i == 0:
return 1
return i*fact(i-1)
test = ['a','b','c','d','e']
permus = permutations(test)
print permus
print fact(len(test)), len(permus)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment