From 1d9b1f47b2cc8f248e1969b0a8f85850c3d01a72 Mon Sep 17 00:00:00 2001 From: Tithi Joshi Date: Fri, 23 Jan 2026 11:12:56 +0530 Subject: [PATCH] docs: add module-level docstring to palindrome algorithms Updated docstring for clarity and improved code readability. Adjusted comments and formatting for better understanding. --- strings/palindrome.py | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/strings/palindrome.py b/strings/palindrome.py index e765207e5942..45993b12aef6 100644 --- a/strings/palindrome.py +++ b/strings/palindrome.py @@ -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 @@ -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()) @@ -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: @@ -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)) @@ -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: @@ -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") @@ -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")