Python recursion permutations

前端 未结 9 1068
自闭症患者
自闭症患者 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:44

    def permute(s):
        ch = list(s)
        if len(ch) == 2:
            per = ch[1] + ch[0] 
            return [''.join(ch)] + [per]
        if len(ch) < 2:
            return ch
        else:
            return [ init+per for init in ch for per in permute(''.join(ch).replace(init,""))] 
    

提交回复
热议问题