2017-10-14 46 views
1

我有一個函數來測試一個字符串是否是迴文與否:函數返回無,即使我有回到命令

def palindrome(raw_text): 
    # first to convert raw_text to a string of lower case letters and remove the space 
    text = raw_text.lower() 
    text = text.replace(' ', '') 

    print('text is now', text) 
    print('length of text is', len(text)) 
    if len(text) == 1 or len(text) == 0: 
     return True 
    else: 
     if text[0] == text[-1]: 
      print('so far so good') 
      palindrome(text[1:-1]) 
     else: 
      return False 

要清楚的調試,我加了一些打印命令來幫助我。 如果我嘗試:

raw_text = 'abcba' 
print(palindrome(raw_text)) 

我會得到:

text is now abcba 
length of text is 5 
so far so good 
text is now bcb 
length of text is 3 
so far so good 
text is now c 
length of text is 1 
None 

那麼,爲什麼我得到在最後一個無?我確實對len(text) == 1 or 0

return True命令。如果我只是給raw_text = 'a',它會給我:

text is now a 
length of text is 1 
True 
+0

順便說一句,你可以很容易地做到這一點沒有遞歸...除非這是在學習遞歸的練習。 –

+1

@ PM2Ring這確實是練習遞歸。否則,我只會使用[:: - 1]進行比較。 THanks –

回答

3

你忘了正常遞歸。

return palindrome(text[1:-1]) 
+0

GOt it !!!謝謝!!!所以這更多的是遞歸。我需要將該關鍵字添加到問題中 –

0

謝謝你,@Ignacio Vazquez-Abrams提到,我沒有正確遞歸。其實代碼並不需要這麼複雜。 我把它修改爲:

def palindrome(raw_text): 
    # first to convert raw_text to a string of lower case letters and remove the space 
    text = raw_text.lower() 
    text = text.replace(' ', '') 

    print('text is now', text) 
    print('length of text is', len(text)) 

    if len(text) <= 3: 
     return text[0] == text[-1] 
    else: 
     return text[0] == text[-1] and palindrome(text[1:-1])