簡體   English   中英

Python中遞歸函數的說明

[英]Explanation of Recursive Function in 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  
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 
if s == '':    
        return [s]

如果它是空字符串,則沒有其他字謎,請返回僅包含該空字符串的列表。

除此以外,

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

s分隔為第一個字符( s[0] )和所有其他字符的子字符串( s[1:] )。 再次調用該函數以查找子字符串的所有字詞(都是w ),

for pos in range(len(w)+1):
        ans.append(w[:pos] + s[0] + w[pos:])

然后針對其中每一個,將s的第一個字符插入w內的任何可能位置( pos )。

這是您的函數,帶有一些打印語句,可幫助您了解發生了什么。

def anagrams(s):
    if s == '':    
        return [s]
    else:
        ans = []
        level = len(s)
        for w in anagrams(s[1:]):
            print('level %d, s[0]: %s, w: %s' % (level, s[0], w))
            for pos in range(len(w)+1): 
                ans.append(w[:pos] + s[0] + w[pos:])
    return ans 

嘗試:

1。

anagrams('a')

輸出:

level 1, s[0]: a, w: 

2。

anagrams('ba')

輸出:

level 1, s[0]: a, w: 
level 2, s[0]: b, w: a

3。

anagrams('cba')

level 1, s[0]: a, w: 
level 2, s[0]: b, w: a
level 3, s[0]: c, w: ba
level 3, s[0]: c, w: ab

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM