Skip to content

permutations implemented in Python

In case you can’t use Python’s itertools or in case you want a simple, recursive python implementation for a permutation of a list:

def perm(a,k=0):
print a
for i in xrange(k,len(a)):
a[k],a[i] = a[i],a[k]
perm(a, k+1)
a[k],a[i] = a[i],a[k]



[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]

This Python implementation is based in the algorithm presented in the book Computer Algorithms by Horowitz, Sahni and Rajasekaran.

Published inenglish

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *