@@ -83,24 +83,33 @@ def is_palindrome_slice(s: str) -> bool:
8383
8484def is_palindrome_ignore_case_and_spaces (s : str ) -> bool :
8585 """
86- Return True if s is a palindrome, ignoring case and spaces .
86+ Return True if s is a palindrome, ignoring case, spaces, and punctuation .
8787 Otherwise return False.
8888
8989 >>> is_palindrome_ignore_case_and_spaces("A man a plan a canal Panama")
9090 True
9191 >>> is_palindrome_ignore_case_and_spaces("Was it a car or a cat I saw?")
92- False
92+ True
9393 >>> is_palindrome_ignore_case_and_spaces("Hello World")
9494 False
9595 >>> is_palindrome_ignore_case_and_spaces("Never Odd or Even")
9696 True
9797 >>> is_palindrome_ignore_case_and_spaces("")
9898 True
9999 """
100- s = s . lower (). replace ( " " , "" )
100+ s = "" . join ( char . lower () for char in s if char . isalnum () )
101101 return s == s [::- 1 ]
102102
103103
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+
104113def benchmark_function (name : str ) -> None :
105114 stmt = f"all({ name } (key) == value for key, value in test_data.items())"
106115 setup = f"from __main__ import test_data, { name } "
@@ -113,17 +122,18 @@ def benchmark_function(name: str) -> None:
113122 for key , value in test_data .items ():
114123 assert is_palindrome (key ) == is_palindrome_recursive (key )
115124 assert is_palindrome (key ) == is_palindrome_slice (key )
116- assert is_palindrome (key ) == is_palindrome_ignore_case_and_spaces (key )
117125 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
118128 print ("a man a plan a canal panama" )
119129
120- # finished 500,000 runs in 0.46793 seconds
130+ # finished 500,000 runs in 1.90863 seconds
121131 benchmark_function ("is_palindrome_slice" )
122- # finished 500,000 runs in 0.85234 seconds
132+ # finished 500,000 runs in 2.80057 seconds
123133 benchmark_function ("is_palindrome" )
124- # finished 500,000 runs in 1.32028 seconds
134+ # finished 500,000 runs in 4.50983 seconds
125135 benchmark_function ("is_palindrome_recursive" )
126- # finished 500,000 runs in 2.08679 seconds
136+ # finished 500,000 runs in 6.81874 seconds
127137 benchmark_function ("is_palindrome_traversal" )
128- # finished 500,000 runs in 0.99769 seconds
138+ # finished 500,000 runs in 10.64074 seconds
129139 benchmark_function ("is_palindrome_ignore_case_and_spaces" )
0 commit comments