Python palindrome program not working

后端 未结 7 815
后悔当初
后悔当初 2021-01-26 12:49

I\'ve written a simple program in python which checks if the sentence is palindrome. But I can\'t figure out why isn\'t it working. The results is always False. Does anyone know

7条回答
  •  一个人的身影
    2021-01-26 13:25

    Since the mistake is already explained and the obvious s == s[::-1] is already taken, I'll just throw a possibly minimal version of the original into the mix:

    def isPalindrome(s):
        s = s.strip().lower()
        return not s or s[0] == s[-1] and isPalindrome(s[1:-1])
    

    Note that you don't need replace(" ", ""). Space on the outside is removed with strip() now, and spaces on the inside will be removed by the strip() later, in a call deeper into the recursion (if we don't stop earlier because a s[0] == s[-1] fails).

提交回复
热议问题