2013-12-09 61 views
0
def algae(S, n): 
    """ 
    Print S rewritten with the algae rule to recursion depth n 
    """ 
    al = {'A': 'AB', 'B': 'A'} 
    # Base case 
    if n == 0: 
     return S 
    # Transform each symbol in S 
    for symbol in S: 
     S += algae(al[symbol], n - 1) 

print(algae('A', 5)) 

嗨,任何人都可以解釋爲什麼打印該功能的我接收到錯誤的結果時:遞歸返回

TypeError: Can't convert 'NoneType' object to str implicitly 

這是指第11行(S + =藻類(人[符號] ,n - 1))

+1

如果n!= 0,你的函數沒有返回。這就是爲什麼你得到一個'NoneType'錯誤。你馬上就打電話給藻類(x,4),它不會返回任何東西。 –

回答

3

編輯:

這是你的腳本的一個工作版本:

def algae(S, n): 
    """ 
    Print S rewritten with the algae rule to recursion depth n 
    """ 
    al = {'A': 'AB', 'B': 'A'} 
    if n == 0: 
     return S 
    # Make a new string to build on 
    mystr = "" 
    for symbol in S: 
     # Add the translation to the new string 
     mystr += al[symbol] 
    # Recursively call the function, passing in the string 
    return algae(mystr, n-1) 

print(algae('A', 5)) 

輸出:

ABAABABAABAAB 

注意:如果你願意,你可以使這個@Blckknght說:

def algae(S, n): 
    """ 
    Print S rewritten with the algae rule to recursion depth n 
    """ 
    al = {'A': 'AB', 'B': 'A'} 
    if n == 0: 
     return S 
    mystr = "".join(al[c] for c in S) 
    return algae(mystr, n-1) 

print(algae('A', 5)) 
+0

感謝您的回答,輸出應該是事實上的:'ABAABABAABAAB'還有什麼不對? –

+0

@ user2850514 - 是的,你的算法有點不合適。看我的編輯。 – iCodez

+0

請注意,創建新字符串的更多「Pytonic」方式應該是'mystr =「」.join(對於S中的c)[al] [c]'。字符串是不可變的,所以你對它們做的每一個'+ ='都需要整個字符串的一個拷貝,如果字符串變長,這個拷貝可能非常慢。 CPython有一些特殊的優化可以讓它在某些時候更快,但是你不應該依賴那個實現特定的行爲。 – Blckknght

3

n != 0,你的代碼落在函數的末尾。在Python中,這相當於返回None。您需要爲遞歸情況添加return語句。

+0

添加'return'會返回一些內容,但不幸的是不會寫入內容。我已將它添加到循環外部的'S + = algae(al [symbol],n - 1)'之下。 –

+0

@ user2850514:對不起,我的意思是你必須返回* *(可能是'S')。一個空的'return'也返回'None'。 –

0

n不爲0的情況下,algae從未return什麼事,所以Python隱含給它的None返回值。接下來algae調用然後試圖做S += None,因爲這樣會產生錯誤。將return S添加到您的函數的末尾以解決此問題。

0

您在功能末尾缺少「return S」。

0

工作版本沒有遞歸(從來不喜歡遞歸)

def algae(S, n): 
    al = {'A': 'AB', 'B': 'A'} 
    for i in range(n): 
     newS = '' 
     for i in range(len(S)): 
      newS += al[S[i]] 
     S = newS 
    return S 

print(algae('A', 5)) 
+0

我不確定(所以你的答案是有效的),但我認爲OP需要使用遞歸,因爲這是一個學校作業。 – iCodez

+0

不一定是一項任務,但我現在正在進行一個基於個人遞歸的項目,並且在這方面遇到麻煩。 –