All Permutations of a String in Python (Recursive)

前端 未结 5 2214
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 10:11

    This kind of thing is a nice place for generators (https://docs.python.org/3.3/tutorial/classes.html#generators), and yield.

    Try something like this (not tested):

    def permute_string(s):
        if len(s) <= 1:   #  "" and 1 char strings are their all their own permutaions.
            yield s
            return
    
        head = s[0] # we hold on to the first character
        for tail in permute_string(s[1:]) :   # permute the rest
            yield head + tail
    
    
    # main
    for permutation in permute_string(s) :
        print(permutation)
    

    This is the classic permutation algorithm: you keep the first character and prepend it to all permutations of the remaining characters. This particular function is a python generator: that means it can keep running while yielding its results one-by-one. In this case, it makes it easier to concentrate on the algorithm without worrying about the details of how to get the data back to the caller.

提交回复
热议问题