Generate all permutations of a list





10
Date Submitted Wed. Oct. 11th, 2006 2:41 PM
Revision 1 of 1
Beginner nil_ptr
Tags permutations | permute | python
Comments 1 comments
This is snippet of code solves the interesting (and specialized) problem of generating all permutations of a list. I hope you like recursion. For exmaple:

permute( [0,1,2] )

would return

[[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]


def permute( values, perms = list(), cur_perm = list() ):
    if len( values ) == 0:
        perms.append( cur_perm )
    else:
        for value in values:
            new_values = values[:]
            new_values.remove( value )
            new_perm = cur_perm[:]
            new_perm.append( value )
            permute( new_values, cur_perm = new_perm )
    return perms

 

Nils Tikkanen

Comments

Comments Great piece of code
Fri. Oct. 13th, 2006 7:32 AM    Scripter bertheymans

Voting