File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 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'
You can’t perform that action at this time.
0 commit comments