From 5ab1527f0c35a8954384f98e1a312b561d0f4e39 Mon Sep 17 00:00:00 2001 From: hafsaafzal6314 Date: Sat, 19 Oct 2024 15:26:54 +0530 Subject: [PATCH] Update palindrome_checker.py --- palindrome_checker.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/palindrome_checker.py b/palindrome_checker.py index c0fdc30..1fc2ce7 100644 --- a/palindrome_checker.py +++ b/palindrome_checker.py @@ -1,7 +1,23 @@ -# palindrome_checker.py +import re + def is_palindrome(s): - return s == s[::-1] + # Normalize the string: remove non-alphanumeric characters and convert to lowercase + normalized_s = re.sub(r'[^A-Za-z0-9]', '', s).lower() + + # Early exit for trivial cases + if len(normalized_s) <= 1: + return True + + # Check for palindrome + left, right = 0, len(normalized_s) - 1 + while left < right: + if normalized_s[left] != normalized_s[right]: + return False + left += 1 + right -= 1 + + return True if __name__ == "__main__": - word = input("Enter a word: ") + word = input("Enter a word or phrase: ") print(f"{word} is a palindrome: {is_palindrome(word)}")