All Permutations of a String in Python (Recursive)

前端 未结 5 2280
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 09:06

I need a kick in the head on this one. I have the following recursive function defined:

def perms(s):
  if(len(s)==1):
    return s

  res = \'\'
  for x in          


        
5条回答
  •  长情又很酷
    2020-12-24 09:59

    Not sure about efficiency but this should work too.

    def find_permutations(v):
        if len(v) > 1:
            for i in perms(v):
                nv = i[1:]
                for j in perms(nv):
                    print(i[0] + j)
        else:
            print(v)
    
    
    def perms(v):
        if not hasattr(perms, 'original'):
            perms.original = v
            perms.list = []
        nv = v[1:] + v[0]
        perms.list.append(nv)
        if perms.original == nv:
            l = perms.list
            del perms.original
            del perms.list
            return l
        return perms(nv)
    
    find_permutations('abc')
    

提交回复
热议问题