Python recursion permutations

前端 未结 9 1069
自闭症患者
自闭症患者 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 19:53

    Recursively, think about the base case and build from that intuition.

    1) What happens when there's only one character 'c'? There's only one permutation of that element, and so we return a list containing only that element.

    2) How can we generate the next permutation given the last one? Adding an additional letter 'a' at all possible positions in the previous permutation 'c' gives us 'ca', 'ac'.

    3) We can continue building larger and larger permutations by adding an additional character at all possible positions in each earlier permutation.

    The following code returns a list of one character if the string has one character or less. Otherwise, for all permutations not including the last character in the string s[-1], we generate a new string for each position where we could include that character and append the new string to our current list of permutations.

    def permutations(s):
        if len(s) <= 1:
            return [s]
        else:
            perms = []
            for e in permutations(s[:-1]):
                for i in xrange(len(e)+1):
                    perms.append(e[:i] + s[-1] + e[i:])
            return perms
    

提交回复
热议问题