2020-05-22 09:57:23 +00:00
|
|
|
def is_palindrome(s: str) -> bool:
|
2020-04-19 16:35:36 +00:00
|
|
|
"""
|
2022-10-23 16:12:49 +00:00
|
|
|
Determine if the string s is a palindrome.
|
|
|
|
|
|
|
|
>>> is_palindrome("A man, A plan, A canal -- Panama!")
|
2020-04-19 16:35:36 +00:00
|
|
|
True
|
|
|
|
>>> is_palindrome("Hello")
|
|
|
|
False
|
2020-05-22 09:57:23 +00:00
|
|
|
>>> is_palindrome("Able was I ere I saw Elba")
|
|
|
|
True
|
|
|
|
>>> is_palindrome("racecar")
|
|
|
|
True
|
|
|
|
>>> is_palindrome("Mr. Owl ate my metal worm?")
|
|
|
|
True
|
2020-04-19 16:35:36 +00:00
|
|
|
"""
|
2022-10-23 16:12:49 +00:00
|
|
|
# Since punctuation, capitalization, and spaces are often ignored while checking
|
|
|
|
# palindromes, we first remove them from our string.
|
|
|
|
s = "".join(character for character in s.lower() if character.isalnum())
|
2023-01-04 00:47:15 +00:00
|
|
|
# return s == s[::-1] the slicing method
|
|
|
|
# uses extra spaces we can
|
|
|
|
# better with iteration method.
|
|
|
|
|
|
|
|
end = len(s) // 2
|
|
|
|
n = len(s)
|
|
|
|
|
|
|
|
# We need to traverse till half of the length of string
|
|
|
|
# as we can get access of the i'th last element from
|
|
|
|
# i'th index.
|
|
|
|
# eg: [0,1,2,3,4,5] => 4th index can be accessed
|
|
|
|
# with the help of 1st index (i==n-i-1)
|
|
|
|
# where n is length of string
|
|
|
|
|
2023-03-01 16:23:33 +00:00
|
|
|
return all(s[i] == s[n - i - 1] for i in range(end))
|
2020-04-19 16:35:36 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2022-10-23 16:12:49 +00:00
|
|
|
s = input("Please enter a string to see if it is a palindrome: ")
|
2020-04-19 16:35:36 +00:00
|
|
|
if is_palindrome(s):
|
2022-10-23 16:12:49 +00:00
|
|
|
print(f"'{s}' is a palindrome.")
|
2020-04-19 16:35:36 +00:00
|
|
|
else:
|
2022-10-23 16:12:49 +00:00
|
|
|
print(f"'{s}' is not a palindrome.")
|