Check Palindrome String Recursively
Check text palindromes recursively with case-insensitive outer comparisons. Students trim matching ends, stop on a mismatch, and retain spaces and punctuation.
1def is_palindrome(s):2 # Base case3 if len(s) <= 1:4 return True56 # Check first and last7 if s[0].lower() != s[-1].lower():8 return False910 # Recurse on middle11 return is_palindrome(s[1:-1])1213# Test14text = input("Enter a string: ")15if is_palindrome(text):16 print("Palindrome")17else:18 print("Not a palindrome")
Output
Enter a string: racecar Palindrome Enter a string: hello Not a palindrome
In this one
- Compare outer characters
- Normalize comparison case
- Shrink both ends
How it works
- 1
Return true for zero or one remaining character.
- 2
Reject unequal lowercase outer characters.
- 3
Otherwise recurse on s[1:-1].
Edge cases
Does empty text pass?
Does empty text pass?
Yes. It has no conflicting pair.
Are spaces ignored?
Are spaces ignored?
No. They remain part of the comparison.
What's going on
The function compares the first and last characters after lowercasing them. A mismatch returns false immediately; a match recurses on the middle slice.
Zero or one remaining character returns true. For Level, each outer pair matches. Spaces and punctuation are not removed, so a phrase that is a palindrome only after cleanup may fail. The shrinking slices and calls consume memory.
Does empty text pass? Yes. It has no conflicting pair.
Are spaces ignored? No. They remain part of the comparison.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What happens after a matching pair?
Pick an answer to check it.
Question 2
Does empty text pass?
Pick an answer to check it.
Questions people ask
Does empty text pass?
Yes. It has no conflicting pair.
Are spaces ignored?
No. They remain part of the comparison.
What happens after a matching pair?
Check s[1:-1].
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum