1- # Algorithms to determine if a string is palindrome
1+ """Algorithms to determine whether a string is a palindrome.
2+
3+ This module provides multiple implementations of palindrome checking
4+ along with basic benchmarking utilities.
5+ """
26
37from timeit import timeit
48
1418 "abcdba" : False ,
1519 "AB" : False ,
1620}
21+
1722# Ensure our test data is valid
1823assert all ((key == key [::- 1 ]) is value for key , value in test_data .items ())
1924
@@ -25,7 +30,6 @@ def is_palindrome(s: str) -> bool:
2530 >>> all(is_palindrome(key) is value for key, value in test_data.items())
2631 True
2732 """
28-
2933 start_i = 0
3034 end_i = len (s ) - 1
3135 while start_i < end_i :
@@ -47,12 +51,6 @@ def is_palindrome_traversal(s: str) -> bool:
4751 end = len (s ) // 2
4852 n = len (s )
4953
50- # We need to traverse till half of the length of string
51- # as we can get access of the i'th last element from
52- # i'th index.
53- # eg: [0,1,2,3,4,5] => 4th index can be accessed
54- # with the help of 1st index (i==n-i-1)
55- # where n is length of string
5654 return all (s [i ] == s [n - i - 1 ] for i in range (end ))
5755
5856
@@ -65,10 +63,9 @@ def is_palindrome_recursive(s: str) -> bool:
6563 """
6664 if len (s ) <= 1 :
6765 return True
68- if s [0 ] == s [len ( s ) - 1 ]:
66+ if s [0 ] == s [- 1 ]:
6967 return is_palindrome_recursive (s [1 :- 1 ])
70- else :
71- return False
68+ return False
7269
7370
7471def is_palindrome_slice (s : str ) -> bool :
@@ -84,7 +81,7 @@ def is_palindrome_slice(s: str) -> bool:
8481def benchmark_function (name : str ) -> None :
8582 stmt = f"all({ name } (key) is value for key, value in test_data.items())"
8683 setup = f"from __main__ import test_data, { name } "
87- number = 500000
84+ number = 500_000
8885 result = timeit (stmt = stmt , setup = setup , number = number )
8986 print (f"{ name :<35} finished { number :,} runs in { result :.5f} seconds" )
9087
@@ -94,13 +91,8 @@ def benchmark_function(name: str) -> None:
9491 assert is_palindrome (key ) is is_palindrome_recursive (key )
9592 assert is_palindrome (key ) is is_palindrome_slice (key )
9693 print (f"{ key :21} { value } " )
97- print ("a man a plan a canal panama" )
9894
99- # finished 500,000 runs in 0.46793 seconds
10095 benchmark_function ("is_palindrome_slice" )
101- # finished 500,000 runs in 0.85234 seconds
10296 benchmark_function ("is_palindrome" )
103- # finished 500,000 runs in 1.32028 seconds
10497 benchmark_function ("is_palindrome_recursive" )
105- # finished 500,000 runs in 2.08679 seconds
10698 benchmark_function ("is_palindrome_traversal" )
0 commit comments