-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathreverse_string.py
More file actions
45 lines (34 loc) · 1.15 KB
/
reverse_string.py
File metadata and controls
45 lines (34 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
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'