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
I presume this is an assignment and the recursion is necessary, obviously return word == word[::-1]
is simpler but is not really relevant. You can write your recursive function a bit more succinctly:
def isPalindrome(word):
if not word:
return True
return word[0] == word[-1] and isPalindrome(word[1:-1])
word[0] == word[-1]
will either be True
or False
so you will either reach an empty string where not word
will True
so the recursion ends and the function returns True
or word[0] == word[-1]
will be False
so the function will return False
as and isPalindrome(word[1:-1])
will never be evaluated.
I would also maybe do the lowering outside of the function:
def isPalindrome(word):
if not word:
return True
return word[0] == word[-1] and isPalindrome(word[1:-1])
sentence = input("Enter a sentence: \n")
sentence = sentence.strip().lower()
sentence = sentence.replace(" ", "")
if isPalindrome(sentence):
print("The sentence %s is palindrome." % sentence)
else:
print("The sentence %s is NOT palindrome" % sentence)