猿问

Python中递归函数的解释

我是 Python 的新手,并试图将我的头放在递归函数上。我理解整体概念,但我遇到了一个我似乎无法完全理解它在做什么的例子。对正在发生的事情进行逐步细分将是理想的,请提前感谢您的帮助。


def anagrams(s):

    if s == '':    

        return [s]

    else:

        ans = []

        for w in anagrams(s[1:]): 

            for pos in range(len(w)+1):

                ans.append(w[:pos] + s[0] + w[pos:])

    return ans  


九州编程
浏览 135回答 2
2回答

米琪卡哇伊

def anagrams(s):&nbsp; &nbsp; # if argument <s> is a blank String&nbsp; &nbsp; if s == '':&nbsp; &nbsp; &nbsp; &nbsp; # return a list is just <s> in it&nbsp; &nbsp; &nbsp; &nbsp; return [s]&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; # create a List&nbsp; &nbsp; &nbsp; &nbsp; ans = []&nbsp; &nbsp; &nbsp; &nbsp; # for each String character in calling this function recursively,&nbsp; &nbsp; &nbsp; &nbsp; # but removing character 0!&nbsp; &nbsp; &nbsp; &nbsp; for w in anagrams(s[1:]):&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # for character position number starting at 0 and ending at&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # the length of the returned value of the recursed function&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # plus 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for pos in range(len(w)+1):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # append a string with the following concatenation:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # - the returned value's string from position 0 to position <pos>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # - the character at position 0 of <s>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # - the returned value's string from position <pos> to the end&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ans.append(w[:pos] + s[0] + w[pos:])&nbsp; &nbsp; # return the list&nbsp; &nbsp; return ans&nbsp;
随时随地看视频慕课网APP

相关分类

Python
我要回答