Python coding practice

Implement is_palindrome(s)

Write a recursive Python function that returns True if a string reads the same forwards and backwards, and False otherwise. The trick is to compare the outer two characters and recurse on everything in between.

The problem

A string is a palindrome if its first and last characters match and the substring in between is also a palindrome. Strings of length 0 or 1 are trivially palindromes — those are your base cases.

is_palindrome("racecar")
"r" == "r" → True, recurse on "aceca"
"a" == "a" → True, recurse on "cec"
"c" == "c" → True, recurse on "e"
len("e") <= 1 → True ← base case

Your function must pass these tests:

  • is_palindrome("")True
  • is_palindrome("a")True
  • is_palindrome("racecar")True
  • is_palindrome("hello")False
  • is_palindrome("level")True

Write your solution below, then click Run Tests:

Advertisement

Hints

Hint 1 — Negative indices in Python

Python allows negative indices: s[-1] is the last character, equivalent to s[len(s) - 1]. The slice s[1:-1] gives you everything except the first and last character.

Hint 2 — Short-circuiting with and

If the outer characters do not match, the string cannot be a palindrome — you can return False immediately without recursing. Using and handles this automatically: s[0] == s[-1] and is_palindrome(s[1:-1]).

Hint 3 — Full solution
def is_palindrome(s):
    if len(s) <= 1:
        return True
    return s[0] == s[-1] and is_palindrome(s[1:-1])

The and operator short-circuits: if s[0] != s[-1], it returns False without making the recursive call.

More coding problems