Palindrome Check
Easy · 35 XPWrite is_palindrome(s) returning True if s reads the same reversed (ignore case). Print the result for "Level" and "Python".
True False
Lowercase first: s = s.lower(); compare s == s[::-1].
def is_palindrome(s):
s = s.lower()
return s == s[::-1]
print(is_palindrome("Level"))
print(is_palindrome("Python"))
Run your code to check it…
How to approach Palindrome Check
A palindrome reads the same in both directions, so the most direct test is to build the reversed string and compare. In Python the slice s[::-1] walks the string with a step of -1 and returns it reversed.
The prompt says to ignore case, and that is the whole trick: "Level" reversed is "leveL", which is a different string. Normalise first with s.lower(), then compare. Make the function return the boolean rather than print it, so the caller decides what to do with the answer.
Worked through on this data
- "Level" lowercases to "level". Reversed it is still "level", so the comparison is True.
- "Python" lowercases to "python". Reversed it is "nohtyp", so the comparison is False.
- The two prints show True and False, matching the target.
Common mistakes
- Skipping
.lower()makes "Level" fail. - Printing inside the function and returning nothing makes the outer
print()showNoneunder each answer. - Reversing with
s.reverse(): strings have no such method, andreversed(s)returns an iterator, not a string, so comparing it tosis always False.
Time and space
Lowercasing, reversing and comparing each walk the string once: O(n) time and O(n) extra space for the copies. A two-pointer version that compares s[i] with s[-1 - i] needs no copy at all.
Where this shows up
The same normalise-then-compare move is how real systems match usernames, email addresses and search terms: decide what differences do not matter, strip them, then compare.
Take it further
Make "A man, a plan, a canal: Panama" return True by keeping only characters where ch.isalnum() is true before comparing.