diff --git a/src/string_reversal.py b/src/string_reversal.py new file mode 100644 index 00000000..59737f62 --- /dev/null +++ b/src/string_reversal.py @@ -0,0 +1,30 @@ +def reverse_string(s: str) -> str: + """ + Reverse a given string manually without using slice notation or reverse(). + + Args: + s (str): The input string to be reversed. + + Returns: + str: The reversed string. + + Raises: + TypeError: If the input is not a string. + """ + # Validate input is a string + if not isinstance(s, str): + raise TypeError("Input must be a string") + + # Convert string to list of characters for manual reversal + chars = list(s) + + # Manually reverse the list of characters + left, right = 0, len(chars) - 1 + while left < right: + # Swap characters from both ends + chars[left], chars[right] = chars[right], chars[left] + left += 1 + right -= 1 + + # Convert back to string and return + return ''.join(chars) \ No newline at end of file diff --git a/tests/test_string_reversal.py b/tests/test_string_reversal.py new file mode 100644 index 00000000..eec4f28d --- /dev/null +++ b/tests/test_string_reversal.py @@ -0,0 +1,38 @@ +import pytest +from src.string_reversal import reverse_string + +def test_reverse_standard_string(): + """Test reversing a standard ASCII string.""" + assert reverse_string("hello") == "olleh" + assert reverse_string("python") == "nohtyp" + +def test_reverse_empty_string(): + """Test reversing an empty string.""" + assert reverse_string("") == "" + +def test_reverse_palindrome(): + """Test reversing a palindrome.""" + assert reverse_string("racecar") == "racecar" + +def test_reverse_with_spaces(): + """Test reversing a string with spaces.""" + assert reverse_string("hello world") == "dlrow olleh" + +def test_reverse_with_special_characters(): + """Test reversing a string with special characters.""" + assert reverse_string("a1b2c3!@#") == "#@!3c2b1a" + +def test_reverse_unicode_string(): + """Test reversing a string with unicode characters.""" + assert reverse_string("こんにちは") == "はちにんこ" + +def test_invalid_input_type(): + """Test that TypeError is raised for non-string inputs.""" + with pytest.raises(TypeError, match="Input must be a string"): + reverse_string(123) + + with pytest.raises(TypeError, match="Input must be a string"): + reverse_string(None) + + with pytest.raises(TypeError, match="Input must be a string"): + reverse_string(["hello"]) \ No newline at end of file