Sunday, May 20, 2012

How to Implement Permutations in Python

#!/usr/bin/env python

def permutate(l, n, nl):
    if n == 0:
        if len(nl) != len(set(nl)): return
        nl1 = []
        for i in nl: nl1.append(l[i])
        print nl1 
    else:
        n = n - 1 
        nl1 = [x for x in nl] 
        for i in xrange(0, len(l)):
            nl = [x for x in nl1]
            nl.append(i)
            permutate(l, n, nl) 
            del nl[:]

def permutations(l):
    permutate(l, len(l), [])

if __name__ == "__main__":
    permutations([1, 2, 3, 4])

No comments:

Post a Comment