Exercises and Common Problems with Palindromes in Python

"Every common problem you face is an opportunity to turn confusion into clarity and practice into learning."

Learning to work with palindromes in Python is not only fun, but it also helps you improve your skills in string manipulation, loops, functions, and algorithms.

In this section, you’ll find a collection of practical exercises and common problems to strengthen your knowledge.

Exercise 1: Check if a word is a palindrome

Task:
Write a program that asks the user for a word and determines if it is a palindrome.

word = input("Enter a word: ")

if word == word[::-1]:
    print("It is a palindrome")
else:
    print("It is not a palindrome")

Exercise 2: Palindromes in a word list

Task: Given a list of words, filter only those that are palindromes.

words = ["oso", "radar", "python", "civic", "reconocer"]

palindromes = [w for w in words if w == w[::-1]]

print("Palindromes found:", palindromes)

Output:

Palindromes found: ['oso', 'radar', 'civic', 'reconocer']

Exercise 3: Palindromes ignoring case and accents

Task: Improve the program so it doesn’t matter if the word is uppercase or lowercase, and also remove accents before checking.

import unicodedata

def normalize(word):
    word = word.lower()
    word = ''.join(
        c for c in unicodedata.normalize('NFD', word)
        if unicodedata.category(c) != 'Mn'
    )
    return word

word = input("Enter a word: ")
word_norm = normalize(word)

if word_norm == word_norm[::-1]:
    print("It is a palindrome")
else:
    print("It is not a palindrome")

Exercise 4: Count how many palindromes are in a list

Task: Given a list of words, show how many are palindromes.

words = ["oso", "luz", "radar", "casa", "ana"]

count = sum(1 for w in words if w == w[::-1])
print("Number of palindromes:", count)

Output:

Number of palindromes: 3

Common Problems when Working with Palindromes

  1. Case sensitivity

  2. "Oso" may not be detected as a palindrome if not converted to lowercase.

  3. Spaces and punctuation marks

  4. Phrases like "anita lava la tina" must be cleaned before checking.

  5. Accents and special characters

  6. Words like "reconocér" may give false negatives if accents are not removed.

  7. Performance in large lists

  8. Using list comprehensions or optimized functions is better than unnecessary loops.

Additional Challenges

  • Detect palindromes in complete phrases, removing spaces and punctuation.
  • Create a recursive program to check palindromes.
  • Write a script that reads a text file and extracts all words that are palindromes.

Practicing with palindrome exercises and problems in Python will help you better master strings, lists, and verification algorithms. They are an excellent foundation for developing programming logic and paving the way toward more advanced projects.

You may also be interested in: