Writing the Palindrome Function for a Coding Test
- python
- coding test
A while ago I was tasked with writing a function to determine whether a string is a palindrome or not in a coding test. A palindrome is a word, phrase, number, or sequence of characters that reads the same forward and backward, e.g: “abcba”.
My first attempt was to split the text into two parts, and compare both if they are the same. For this reason, I thought that the length of the palindrome should always be odd.
def is_palindrome(s):
# Single char is always a palindrome
if len(s) == 1:
return True
# The length of palindrome should be odd (?)
if len(s) % 2 == 0:
return False
# Split the left and right part
middle = math.ceil(len(s) / 2)
left = s[:middle]
right = s[middle-1:]
# Check if palindrome
return left == right[::-1]
And then I thought, why should I divide the string into two parts? I can just compare the string and the reversed version and it still gives the same result.
def is_palindrome(s):
# The length can be odd or even...
# Check if palindrome
return s == s[::-1]
The function successfully detected most of the palindrome sentences, but failed to detect some. After the coding test session ended, I asked my AI Assistant to generate some complex palindromes, and it gave me this:
- “A man, a plan, a canal, Panama!”
- “Evil is a name of a foeman, as I live.”
- “Mr. Owl ate my metal worm.”
- “Was it a car or a cat I saw?”
- “Rise to vote, sir.”
God, I forgot that they can contain special characters! Fortunately the solusion is simple with the regex module.
import re
def is_palindrome(s):
# Remove special characters
s = re.sub(r'[^\w]', '', s).lower()
# Check if palindrome
return s == s[::-1]
And now it passes the tests for complex palindromes.