Python recursion permutations

前端 未结 9 1080
自闭症患者
自闭症患者 2020-11-27 19:24

Im having trouble trying to make a permutation code with recursion. This is suppose to return a list back to the use with all the posible position for each letter. so for t

9条回答
  •  萌比男神i
    2020-11-27 19:54

    You want to do recursion, so you first have to find out how the recursion would work. In this case it is the following:

    permutation [a,b,c,...] = [a + permutation[b,c,...], b + permutation[a,c,..], ...]
    

    And as a final condition:

    permutation [a] = [a]
    

    So the recursion splits up the list in sublists with one element extracted each time. Then this element is added to the front of each of the permutations of the sublist.

    So in pseudo-code:

    def permutation(s):
       if len(s) == 1:
         return [s]
    
       perm_list = [] # resulting list
       for a in s:
         remaining_elements = [x for x in s if x != a]
         z = permutation(remaining_elements) # permutations of sublist
    
         for t in z:
           perm_list.append([a] + t)
    
       return perm_list
    

    Does this help?

提交回复
热议问题