Brain teasers: Palindromes

A palindrome is a word, number, phrase, or other sequence of symbols that reads the same backward as forward. The simplest examples of palindromes include madam, racecar, mom, toot, rotor, and many others...

Brain teasers: Palindromes

This time we will face a common challenge we encounter during job interviews. The problem is as follows:

Given a string, write a function that will check if it is a palindrome.

First of all, let’s find out what a palindrome is.

💡
A palindrome is a word, number, phrase, or other sequence of symbols that reads the same backward as forward.

The simplest examples of palindromes include madam, racecar, mom, toot, rotor, and many others.

Now we are ready to start figuring the problem out. If you need to refresh your knowledge, follow the link below. 👇👇👇

Exploring Python
Python is frequently utilized in creating websites and software, as well as for automating tasks, analyzing data, and visualizing information.

Solution #1

The most naive approach to checking whether a given string is a palindrome is to loop through each character and check the first character against the last character of the string, the second to the second to last, and so on. If any character does not match, the specified string is NOT a palindrome.

def check_palindrome(word: str) -> bool:
    length: int = len(word)
    for i in range(0, int(length / 2)):
        if word[i] != word[length - i - 1]:
            return False
    return True


if __name__ == '__main__':
    word: str = input(f'Provide a word\n')
    is_palindrome: bool = check_palindrome(word)
    print(f'Is "{word}" a palindorme? {is_palindrome}')

We have created the check_palindrome() function that takes as an argument the provided text and returns the boolean value indicating whether the provided string is palindrome or not. Inside the function, we loop through the range from 0 to the length of the word divided by 2. When iterating we check the first character with the last one, the second character with the second-to-last, and so on. In the main section we prompt the user for a word, call the check_palindrome() function, and then print the result.

❯ python3 main.py
Provide a word
racecar
Is "racecar" a palindorme? True
Provide a word
cow
Is "cow" a palindorme? False

Executing the scripts shows correctly that a racecar is a palindrome while a cow is not, so it works perfectly!

Solution #2

The previous solution is very naive and does not use leverage from many built-in functions provided in Python. This time we are going to refactor the check_palindorme() function to use the reversed() function and string's join() method.

def check_palindrome(word: str) -> bool:
    reversed_word: str = ''.join(reversed(word))
    return word == reversed_word

if __name__ == '__main__':
    word: str = input(f'Provide a word\n')
    is_palindrome: bool = check_palindrome(word)
    print(f'Is "{word}" a palindorme? {is_palindrome}')

The reversed() function returns a reverse iterator that starts iterating from the end. The iterator is passed into the join() method to form a string. '' are used to provide a character used to join elements coming from the iterator - in our particular case - it is just an empty string. This way we obtain a new reversed string. Finally, we compare it with the original one.

❯ python3 main.py
Provide a word
racecar
Is "racecar" a palindorme? True
Provide a word
cow
Is "cow" a palindorme? False

Still works! 😁

Solution #3

We can make the previous solution even more concise by using the square brackets [].

def check_palindrome(word: str) -> bool:
    return word == word[::-1]

if __name__ == '__main__':
    word: str = input(f'Provide a word\n')
    is_palindrome: bool = check_palindrome(word)
    print(f'Is "{word}" a palindorme? {is_palindrome}')

Now the logic boils down to just a single line of code!

❯ python3 main.py
Provide a word
racecar
Is "racecar" a palindorme? True
Provide a word
cow
Is "cow" a palindorme? False

Flawless victory! 😂

Summary

We learned that a palindrome is a word, number, phrase, or other sequence of symbols that reads the same backward as forward. We have provided three ways to check whether text is a palindrome. The first solution is the most naive and involves iterating over each character in the sequence. The second solution uses built-in functions and methods to reverse text for comparison. The last solution is the most concise and uses square brackets to reverse the string. We must be very careful when choosing the right measures because they strongly affect the readability and maintainability of the code.

What's next?

Subscribe to receive more posts like this directly to your email!

Ideas💡, questions❔❓ ? Feel free to start the discussion 🗣️🎙️!

Ready for more challenges? 👇👇👇

Python Basics: Brain teasers
In the world of programming, the road to expertise is paved with challenges. Don’t shy away from solving programming problems; instead, embrace them as opportunities for growth.

References

Palindrome - Wikipedia
Built-in Functions
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a…
Built-in Types
The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some colle…