1
1
# Algorithms to determine if a string is palindrome
2
2
3
+ from timeit import timeit
4
+
5
+
3
6
test_data = {
4
7
"MALAYALAM" : True ,
5
8
"String" : False ,
@@ -33,6 +36,25 @@ def is_palindrome(s: str) -> bool:
33
36
return True
34
37
35
38
39
+ def is_palindrome_traversal (s : str ) -> bool :
40
+ """
41
+ Return True if s is a palindrome otherwise return False.
42
+
43
+ >>> all(is_palindrome_traversal(key) is value for key, value in test_data.items())
44
+ True
45
+ """
46
+ end = len (s ) // 2
47
+ n = len (s )
48
+
49
+ # We need to traverse till half of the length of string
50
+ # as we can get access of the i'th last element from
51
+ # i'th index.
52
+ # eg: [0,1,2,3,4,5] => 4th index can be accessed
53
+ # with the help of 1st index (i==n-i-1)
54
+ # where n is length of string
55
+ return all (s [i ] == s [n - i - 1 ] for i in range (end ))
56
+
57
+
36
58
def is_palindrome_recursive (s : str ) -> bool :
37
59
"""
38
60
Return True if s is a palindrome otherwise return False.
@@ -58,9 +80,22 @@ def is_palindrome_slice(s: str) -> bool:
58
80
return s == s [::- 1 ]
59
81
60
82
83
+ def benchmark_function (name : str ) -> None :
84
+ setup = f"from __main__ import test_data, { name } "
85
+ number = 100000
86
+ res = timeit (f"all({ name } (key) is value for key, value in test_data.items())" , setup = setup , number = number )
87
+ print (f"{ name :<35} finished { number } runs in { res :.5f} seconds" )
88
+
89
+
61
90
if __name__ == "__main__" :
62
91
for key , value in test_data .items ():
63
92
assert is_palindrome (key ) is is_palindrome_recursive (key )
64
93
assert is_palindrome (key ) is is_palindrome_slice (key )
65
94
print (f"{ key :21} { value } " )
66
95
print ("a man a plan a canal panama" )
96
+
97
+ benchmark_function ("is_palindrome" ) # finished 100000 runs in 0.33785 seconds
98
+ benchmark_function ("is_palindrome_traversal" ) # finished 100000 runs in 0.70002 seconds
99
+ benchmark_function ("is_palindrome_recursive" ) # finished 100000 runs in 0.48514 seconds
100
+ benchmark_function ("is_palindrome_slice" ) # finished 100000 runs in 0.18703 seconds
101
+
0 commit comments