Skip to content

Commit 5555b58

Browse files
author
muannn
committed
Add reverse_string algorithm with type checking and examples
1 parent e2a78d4 commit 5555b58

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

strings/reverse_string.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
Algorithm: Reverse String
3+
Author: muannn
4+
Description:
5+
This module implements a simple function to reverse an input string.
6+
It is part of the TheAlgorithms/Python open-source collection.
7+
8+
The algorithm takes a string `s` as input and returns the reversed version.
9+
It also handles edge cases such as empty strings and single-character inputs.
10+
11+
Example:
12+
>>> reverse_string("Hello")
13+
'olleH'
14+
15+
>>> reverse_string("OpenAI")
16+
'IAnepO'
17+
"""
18+
19+
def reverse_string(s: str) -> str:
20+
"""
21+
Reverse the given string.
22+
23+
Args:
24+
s (str): The string to be reversed.
25+
26+
Returns:
27+
str: A new string that is the reverse of `s`.
28+
29+
Raises:
30+
TypeError: If the input is not a string.
31+
"""
32+
if not isinstance(s, str):
33+
raise TypeError("Input must be a string.")
34+
35+
# Core logic: Python slicing technique to reverse string
36+
return s[::-1]
37+
38+
39+
if __name__ == "__main__":
40+
# Simple test cases for demonstration
41+
print(reverse_string("Python")) # Expected: 'nohtyP'
42+
print(reverse_string("OpenAI")) # Expected: 'IAnepO'
43+
print(reverse_string("")) # Expected: ''
44+
print(reverse_string("A")) # Expected: 'A'

0 commit comments

Comments
 (0)