I am given word and I have to check if the word is a palindrome. My program works well until I play around with the case of the word.
def isPalindrome(word):
reversedWord = word[::-1]
palindrome = true
for n in range(len(word)):
if(word[n] != reversedWord[i])
palindrome = false
return palindrome
I tried the below code and it works well if I feed the function the word "mom", however it fails when I give it the same word but with a different case "Mom"
def isPalindrome(word):
reversedWord = word[::-1]
palindrome = true
for n in range(len(word)):
if(word[n] != reversedWord[i])
palindrome = false
return palindrome
CodePudding user response:
You are already reversing the string. Just return reversedWord.lower() == word.lower() instead of checking character by character.
CodePudding user response:
You need to normalise the string to either upper- or lower-case.
def isPalindrome(word):
word = word.lower()
return word == word[::-1]
CodePudding user response:
You would have to compare the lowercase version of the word to its reversed version. There is a function in Python that transforms a String to all-lowercase. Search for it and try it out :)
CodePudding user response:
The hex values of m and M in ascii table are different from each other. Since these values are different in logic comparison, the result will be not a polydrome.
CodePudding user response:
You could transform your word into lowercase (or uppercase) and then check if the reversed if it is a palindrome.
def isPalindrome(word):
word = word.lower()
return True if word == word[::-1] else False
isPalindrom("Mom")
returns True
CodePudding user response:
The simplest form to this is where you use Ternary operator and Python String lower() method as given below:
def isPalindrome(word):
return True if (word.lower() == word[::-1].lower()) else False