0

Tom is asked to code the logic to find if a given sentence or a word is a palindrome or not. Help him to code this logic in Python. Remember to do a case insensitive check. Refer the sample input and output statements for more clarifications.

Sample Input 1: Enter the word : Madam

Sample Output 1: Yes, the string is a palindrome !

Sample Input 2: Enter the word : Python

Sample Output 2: No, the string is not a palindrome !

Sample Input 3: Enter the word : Was it a rat I saw

Sample Output 3: Yes, the string is a palindrome !

I've coded as follows:

t1 = input('Enter the word : ').lower() 
if( t1==t1[::-1])
   print('Yes, the string is a palindrome !')
else:
   print('No, the string is not a palindrome !')

Still I am not able to pass all test cases. Can anyone please help me to figure it out?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

3 Answers3

2

The third test-case suggests that spaces shouldn't be considered in the check. So just ignore them, by either of these ways:

t1 = input().lower().replace(' ', '')

or

t1 = ''.join(input().lower().split())
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
1

You should be ignoring characters that aren't letters (like spaces), so you can filter them out then do your check:

t1 = input("Enter the word: ").lower()
# filter out non-letters
t1 = "".join(x for x in t1 if x.isalpha())
if t1 == t1[::-1]:
    print("It is a palindrome")
else:
    print("It is not a palindrome")
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

I really wouldn't use a simple "flip" to compare a palindrome, using a loop is still ideal as it avoids having to manipulate the whole string:

def isPalindrome(word):
    word = word.lower().replace(" ", "")
    start, end = 0, len(word)-1
    while start < end and word[start] == word[end]:
        start += 1
        end -= 1
    return start >= end
fixatd
  • 1,394
  • 1
  • 11
  • 19