LearnFrenzy
Sign in Take a free test

Recursion · Recursion Coding Problems · Question 8

Check a palindrome recursively in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Check palindromes recursively, ignoring case, spaces and punctuation.

Solution
main.py Run
def is_pal(s):
    if len(s) < 2:
        return True
    return s[0] == s[-1] and is_pal(s[1:-1])

def check(text):
    clean = "".join(ch.lower() for ch in text if ch.isalnum())
    return is_pal(clean)

for t in ["Racecar", "Never odd or even", "Python", "Was it a car or a cat I saw?"]:
    print(f"{t!r}: {check(t)}")

Output Verified by running it on Python 3

'Racecar': True
'Never odd or even': True
'Python': False
'Was it a car or a cat I saw?': True

Compare the ends, then recurse on the middle. and short-circuits, so the recursion stops at the first mismatch.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links