Python recursion permutations

前端 未结 9 1084
自闭症患者
自闭症患者 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 20:00

    I know this is a me too, but I think this one might be easier for some folks to understand....

    1. The base case is when the input is just one character.
    2. Setup up a for loop that iterates through each of the letters in the string.
    3. Another for loop recursively permutes through all the other possibilities.

      def permute(s):
      
          out = []
      
          if len(s) == 1:
              out = [s]
          else:
              for i,let in enumerate(s):
                  for perm in permute(s[:i]+s[i+1:]):
                      out += [let+perm]
          return out
      

提交回复
热议问题