Recursive function to develop permutations

Steve Goldman steve_g at ix.netcom.com
Mon Oct 18 20:34:57 EDT 2004


Hi,

I am trying to come up with a way to develop all n-length permutations of a
given list of values.  The short function below seems to work, but I can't
help thinking there's a better way.  Not being a computer scientist, I find
recursive functions to be frightening and unnatural.  I'd appreciate if
anyone can tell me the pythonic idiom to accomplish this.

Thanks for your help,

Steve Goldman

###START CODE###

def permute(list,n,initialize=True):
    """A recursive function that returns a list of all length n ordered
permutations of "list", length k."""
    if initialize:
        global permutation, permutation_list
        permutation=[]    #This list holds the individual permutations.  It
is built one element at a time
        permutation_list=[]    #This list is the list that will contain all
the permutations
    n=n-1    #This counts down for each element of the permutation.  It is a
local variable,
                 #so each subsequent function call has n reduced by one
    for e in list:
        permutation.append(e)
        if n>0:    #that is,the permutation needs additional elements
            permute(list,n,False)
        else:    # the permutation is length n
            permutation_list.append(permutation[:])    #store the completed
permutation
        permutation.pop(-1)    # knock off the last value and go to the next
element in "list"
    return permutation_list


if __name__=='__main__':
    list=['red','white','blue','green']
    print permute(list,3)






More information about the Python-list mailing list