2017-10-14 50 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])