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.
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.
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.
And now it passes the tests for complex palindromes.