Skip to content

Merge and add benchmarks to palindrome algorithms in the strings/ directory #8749

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 25, 2023
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,7 @@
* [Hexagonal Number](maths/hexagonal_number.py)
* [Integration By Simpson Approx](maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py)
* [Is Palindrome](maths/is_palindrome.py)
* [Is Square Free](maths/is_square_free.py)
* [Jaccard Similarity](maths/jaccard_similarity.py)
* [Juggler Sequence](maths/juggler_sequence.py)
Expand Down Expand Up @@ -1154,7 +1155,6 @@
* [Indian Phone Validator](strings/indian_phone_validator.py)
* [Is Contains Unique Chars](strings/is_contains_unique_chars.py)
* [Is Isogram](strings/is_isogram.py)
* [Is Palindrome](strings/is_palindrome.py)
* [Is Pangram](strings/is_pangram.py)
* [Is Spain National Id](strings/is_spain_national_id.py)
* [Is Srilankan Phone Number](strings/is_srilankan_phone_number.py)
Expand Down
41 changes: 0 additions & 41 deletions strings/is_palindrome.py

This file was deleted.

40 changes: 39 additions & 1 deletion strings/palindrome.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Algorithms to determine if a string is palindrome

from timeit import timeit

test_data = {
"MALAYALAM": True,
"String": False,
Expand Down Expand Up @@ -33,14 +35,33 @@ def is_palindrome(s: str) -> bool:
return True


def is_palindrome_traversal(s: str) -> bool:
"""
Return True if s is a palindrome otherwise return False.

>>> all(is_palindrome_traversal(key) is value for key, value in test_data.items())
True
"""
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))


def is_palindrome_recursive(s: str) -> bool:
"""
Return True if s is a palindrome otherwise return False.

>>> all(is_palindrome_recursive(key) is value for key, value in test_data.items())
True
"""
if len(s) <= 1:
if len(s) <= 2:
return True
if s[0] == s[len(s) - 1]:
return is_palindrome_recursive(s[1:-1])
Expand All @@ -58,9 +79,26 @@ def is_palindrome_slice(s: str) -> bool:
return s == s[::-1]


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
result = timeit(stmt=stmt, setup=setup, number=number)
print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds")


if __name__ == "__main__":
for key, value in test_data.items():
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")