Hey everyone! π
Continuing with our coding challenges series! Today we're looking at a classic string manipulation problem: checking for palindromes.
The Problem
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).
Examples:
- "racecar" -> True
- "A man a plan a canal Panama" -> True
- "hello" -> False
The Solution
Here is a clean Python solution that handles case insensitivity and ignores spaces:
def is_palindrome(s):
"""
Checks if a string is a palindrome.
Ignores case and spaces.
"""
s = str.lower(s)
s = s.replace(" ", "")
return s == s[::-1]
# Test cases
print(is_palindrome("wilabaliw"))
# Output: True
print(is_palindrome("A man a plan a canal Panama"))
# Output: True
Code Breakdown
Let's break down how this works:
-
s = str.lower(s)- First, we convert the entire string to lowercase. This ensures that "Racecar" and "racecar" are treated as the same string.
-
s = s.replace(" ", "")- Next, we remove all spaces. This is important for phrases like "A man a plan..." where the spaces don't match up when reversed, but the letters do.
-
return s == s[::-1]- This is the Pythonic magic!
s[::-1]creates a reversed copy of the string. - We simply compare the cleaned original string with its reverse. If they are equal, it returns
True; otherwise,False.
- This is the Pythonic magic!
Short, sweet, and effective!
Stay tuned for more challenges! Happy coding! π»
Top comments (0)