From 5555b5802553a59d81a05cf75759099f421a2f65 Mon Sep 17 00:00:00 2001 From: muannn Date: Thu, 23 Oct 2025 22:09:59 +0800 Subject: [PATCH 1/2] Add reverse_string algorithm with type checking and examples --- strings/reverse_string.py | 44 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 strings/reverse_string.py diff --git a/strings/reverse_string.py b/strings/reverse_string.py new file mode 100644 index 000000000000..54bcd833bbc9 --- /dev/null +++ b/strings/reverse_string.py @@ -0,0 +1,44 @@ +""" +Algorithm: Reverse String +Author: muannn +Description: + This module implements a simple function to reverse an input string. + It is part of the TheAlgorithms/Python open-source collection. + + The algorithm takes a string `s` as input and returns the reversed version. + It also handles edge cases such as empty strings and single-character inputs. + +Example: + >>> reverse_string("Hello") + 'olleH' + + >>> reverse_string("OpenAI") + 'IAnepO' +""" + +def reverse_string(s: str) -> str: + """ + Reverse the given string. + + Args: + s (str): The string to be reversed. + + Returns: + str: A new string that is the reverse of `s`. + + Raises: + TypeError: If the input is not a string. + """ + if not isinstance(s, str): + raise TypeError("Input must be a string.") + + # Core logic: Python slicing technique to reverse string + return s[::-1] + + +if __name__ == "__main__": + # Simple test cases for demonstration + print(reverse_string("Python")) # Expected: 'nohtyP' + print(reverse_string("OpenAI")) # Expected: 'IAnepO' + print(reverse_string("")) # Expected: '' + print(reverse_string("A")) # Expected: 'A' From 1aeff9bb128fd5fdbe2752cf8558c49876f9f694 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 23 Oct 2025 14:15:24 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- strings/reverse_string.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/strings/reverse_string.py b/strings/reverse_string.py index 54bcd833bbc9..e8184b49515d 100644 --- a/strings/reverse_string.py +++ b/strings/reverse_string.py @@ -16,6 +16,7 @@ 'IAnepO' """ + def reverse_string(s: str) -> str: """ Reverse the given string. @@ -38,7 +39,7 @@ def reverse_string(s: str) -> str: if __name__ == "__main__": # Simple test cases for demonstration - print(reverse_string("Python")) # Expected: 'nohtyP' - print(reverse_string("OpenAI")) # Expected: 'IAnepO' - print(reverse_string("")) # Expected: '' - print(reverse_string("A")) # Expected: 'A' + print(reverse_string("Python")) # Expected: 'nohtyP' + print(reverse_string("OpenAI")) # Expected: 'IAnepO' + print(reverse_string("")) # Expected: '' + print(reverse_string("A")) # Expected: 'A'