我有一個函數來測試一個字符串是否是迴文與否:函數返回無,即使我有回到命令
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
順便說一句,你可以很容易地做到這一點沒有遞歸...除非這是在學習遞歸的練習。 –
@ PM2Ring這確實是練習遞歸。否則,我只會使用[:: - 1]進行比較。 THanks –