Skip to content

Commit 48aeff8

Browse files
kaviya-nscclauss
andauthored
Add is_palindrome_ignore_case_and_spaces to strings/palindrome.py (#14907)
* Add is_palindrome_ignore_case_and_spaces to strings/palindrome.py * Address review: handle punctuation, add dedicated test data for new function * Revert unrelated benchmark timing comments per review --------- Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent f0ab75d commit 48aeff8

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

‎strings/palindrome.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,35 @@ def is_palindrome_slice(s: str) -> bool:
8181
return s == s[::-1]
8282

8383

84+
def is_palindrome_ignore_case_and_spaces(s: str) -> bool:
85+
"""
86+
Return True if s is a palindrome, ignoring case, spaces, and punctuation.
87+
Otherwise return False.
88+
89+
>>> is_palindrome_ignore_case_and_spaces("A man a plan a canal Panama")
90+
True
91+
>>> is_palindrome_ignore_case_and_spaces("Was it a car or a cat I saw?")
92+
True
93+
>>> is_palindrome_ignore_case_and_spaces("Hello World")
94+
False
95+
>>> is_palindrome_ignore_case_and_spaces("Never Odd or Even")
96+
True
97+
>>> is_palindrome_ignore_case_and_spaces("")
98+
True
99+
"""
100+
s = "".join(char.lower() for char in s if char.isalnum())
101+
return s == s[::-1]
102+
103+
104+
test_data_ignore_case_and_spaces = {
105+
"A man a plan a canal Panama": True,
106+
"Was it a car or a cat I saw?": True,
107+
"Hello World": False,
108+
"Never Odd or Even": True,
109+
"": True,
110+
}
111+
112+
84113
def benchmark_function(name: str) -> None:
85114
stmt = f"all({name}(key) == value for key, value in test_data.items())"
86115
setup = f"from __main__ import test_data, {name}"
@@ -94,6 +123,8 @@ def benchmark_function(name: str) -> None:
94123
assert is_palindrome(key) == is_palindrome_recursive(key)
95124
assert is_palindrome(key) == is_palindrome_slice(key)
96125
print(f"{key:21} {value}")
126+
for key, value in test_data_ignore_case_and_spaces.items():
127+
assert is_palindrome_ignore_case_and_spaces(key) == value
97128
print("a man a plan a canal panama")
98129

99130
# finished 500,000 runs in 0.46793 seconds
@@ -104,3 +135,5 @@ def benchmark_function(name: str) -> None:
104135
benchmark_function("is_palindrome_recursive")
105136
# finished 500,000 runs in 2.08679 seconds
106137
benchmark_function("is_palindrome_traversal")
138+
# finished 500,000 runs in 4.27493 seconds
139+
benchmark_function("is_palindrome_ignore_case_and_spaces")

0 commit comments

Comments
 (0)