我有一个函数来测试一个字符串是否是回文与否:函数返回无,即使我有回到命令
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 –