亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號