Palindrome Check Two Pointers
Walk two pointers inward from both ends, skipping non-alphanumeric characters and comparing lowercased letters, so punctuation-laden phrases still verify.
Code
def is_palindrome(text):
"""Palindrome check with two pointers comparing mirrored ends."""
left, right = 0, len(text) - 1
while left < right:
if not text[left].isalnum():
left += 1
elif not text[right].isalnum():
right -= 1
elif text[left].lower() != text[right].lower():
return False
else:
left += 1
right -= 1
return True
candidates = ["racecar", "A man, a plan, a canal: Panama!", "hello", ""]
for candidate in candidates:
print(f"{candidate!r} -> {is_palindrome(candidate)}")
print("half comparisons for racecar:", len("racecar") // 2)Output
Captured from a sandboxed run of this snippet in the build pipeline.
'racecar' -> True
'A man, a plan, a canal: Panama!' -> True
'hello' -> False
'' -> True
half comparisons for racecar: 3Reading the snippet
Everything happens inside the function is_palindrome.
One loop does the cycling here: while left < right.
Points of care
- Only built-in APIs appear, leaving no supply chain to audit.
Using it
Signature: def is_palindrome(text)
The demo output is labeled (half comparisons for racecar:); each label names the call that printed it.
The surface worth importing is is_palindrome; the helpers around it are private to the snippet.
Key statements
elif text[left].lower() != text[right].lower():
return False
elif not text[right].isalnum():
right -= 1
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `is_palindrome` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.