为了账号安全,请及时绑定邮箱和手机立即绑定

Python中递归函数的解释

Python中递归函数的解释

九州编程 2021-07-03 04:29:59
我是 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  
查看完整描述

2 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

def anagrams(s):

    # if argument <s> is a blank String

    if s == '':

        # return a list is just <s> in it

        return [s]

    else:

        # create a List

        ans = []

        # for each String character in calling this function recursively,

        # but removing character 0!

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

            # for character position number starting at 0 and ending at

            # the length of the returned value of the recursed function

            # plus 1

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

                # append a string with the following concatenation:

                # - the returned value's string from position 0 to position <pos>

                # - the character at position 0 of <s>

                # - the returned value's string from position <pos> to the end

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

    # return the list

    return ans 


查看完整回答
反对 回复 2021-07-06
  • 2 回答
  • 0 关注
  • 134 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号