Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 9 additions & 17 deletions strings/palindrome.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
# Algorithms to determine if a string is palindrome
"""Algorithms to determine whether a string is a palindrome.

This module provides multiple implementations of palindrome checking
along with basic benchmarking utilities.
"""

from timeit import timeit

Expand All @@ -14,6 +18,7 @@
"abcdba": False,
"AB": False,
}

# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())

Expand All @@ -25,7 +30,6 @@ def is_palindrome(s: str) -> bool:
>>> all(is_palindrome(key) is value for key, value in test_data.items())
True
"""

start_i = 0
end_i = len(s) - 1
while start_i < end_i:
Expand All @@ -47,12 +51,6 @@ def is_palindrome_traversal(s: str) -> bool:
end = len(s) // 2
n = len(s)

# We need to traverse till half of the length of string
# as we can get access of the i'th last element from
# i'th index.
# eg: [0,1,2,3,4,5] => 4th index can be accessed
# with the help of 1st index (i==n-i-1)
# where n is length of string
return all(s[i] == s[n - i - 1] for i in range(end))


Expand All @@ -65,10 +63,9 @@ def is_palindrome_recursive(s: str) -> bool:
"""
if len(s) <= 1:
return True
if s[0] == s[len(s) - 1]:
if s[0] == s[-1]:
return is_palindrome_recursive(s[1:-1])
else:
return False
return False


def is_palindrome_slice(s: str) -> bool:
Expand All @@ -84,7 +81,7 @@ def is_palindrome_slice(s: str) -> bool:
def benchmark_function(name: str) -> None:
stmt = f"all({name}(key) is value for key, value in test_data.items())"
setup = f"from __main__ import test_data, {name}"
number = 500000
number = 500_000
result = timeit(stmt=stmt, setup=setup, number=number)
print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds")

Expand All @@ -94,13 +91,8 @@ def benchmark_function(name: str) -> None:
assert is_palindrome(key) is is_palindrome_recursive(key)
assert is_palindrome(key) is is_palindrome_slice(key)
print(f"{key:21} {value}")
print("a man a plan a canal panama")

# finished 500,000 runs in 0.46793 seconds
benchmark_function("is_palindrome_slice")
# finished 500,000 runs in 0.85234 seconds
benchmark_function("is_palindrome")
# finished 500,000 runs in 1.32028 seconds
benchmark_function("is_palindrome_recursive")
# finished 500,000 runs in 2.08679 seconds
benchmark_function("is_palindrome_traversal")