Skip to content

Commit b42f504

Browse files
committed
refactor: Merge and add benchmarks to palindrome
1 parent edc17b6 commit b42f504

File tree

2 files changed

+35
-41
lines changed

2 files changed

+35
-41
lines changed

Diff for: strings/is_palindrome.py

-41
This file was deleted.

Diff for: strings/palindrome.py

+35
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# Algorithms to determine if a string is palindrome
22

3+
from timeit import timeit
4+
5+
36
test_data = {
47
"MALAYALAM": True,
58
"String": False,
@@ -33,6 +36,25 @@ def is_palindrome(s: str) -> bool:
3336
return True
3437

3538

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+
3658
def is_palindrome_recursive(s: str) -> bool:
3759
"""
3860
Return True if s is a palindrome otherwise return False.
@@ -58,9 +80,22 @@ def is_palindrome_slice(s: str) -> bool:
5880
return s == s[::-1]
5981

6082

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+
6190
if __name__ == "__main__":
6291
for key, value in test_data.items():
6392
assert is_palindrome(key) is is_palindrome_recursive(key)
6493
assert is_palindrome(key) is is_palindrome_slice(key)
6594
print(f"{key:21} {value}")
6695
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

Comments
 (0)