All Permutations of a String in Python (Recursive)

前端 未结 5 2238
被撕碎了的回忆
被撕碎了的回忆 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 10:10

    The result of permutations will be a collection, let's say a list. It will make your code cleaner if you think this way and if required you can join the results into a single string. A simple example will be

    def perms(s):        
        if(len(s)==1): return [s]
        result=[]
        for i,v in enumerate(s):
            result += [v+p for p in perms(s[:i]+s[i+1:])]
        return result
    
    
    perms('abc')
    
    ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
    
    
    print('\n'.join(perms('abc')))
    
    abc
    acb
    bac
    bca
    cab
    cba
    

提交回复
热议问题