Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/string_reversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
def reverse_string(s: str) -> str:
"""
Reverse the given string using a manual character-by-character approach.

Args:
s (str): The input string to be reversed.

Returns:
str: The reversed string.

Raises:
TypeError: If the input is not a string.
"""
# Type checking
if not isinstance(s, str):
raise TypeError("Input must be a string")

# Handle empty string case
if len(s) <= 1:
return s

# Manual string reversal
# Convert string to list of characters for easy manipulation
chars = list(s)

# Two-pointer approach to swap characters
left, right = 0, len(chars) - 1
while left < right:
# Swap characters
chars[left], chars[right] = chars[right], chars[left]

# Move pointers
left += 1
right -= 1

# Convert list back to string and return
return ''.join(chars)
38 changes: 38 additions & 0 deletions tests/test_string_reversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import pytest
from src.string_reversal import reverse_string

def test_reverse_string_basic():
"""Test basic string reversal."""
assert reverse_string("hello") == "olleh"
assert reverse_string("world") == "dlrow"

def test_reverse_string_empty():
"""Test reversing an empty string."""
assert reverse_string("") == ""

def test_reverse_string_single_char():
"""Test reversing a single character string."""
assert reverse_string("a") == "a"

def test_reverse_string_with_spaces():
"""Test reversing a string with spaces."""
assert reverse_string("hello world") == "dlrow olleh"

def test_reverse_string_with_special_chars():
"""Test reversing a string with special characters."""
assert reverse_string("a1b2c3!@#") == "#@!3c2b1a"

def test_reverse_string_with_mixed_chars():
"""Test reversing a string with mixed characters."""
assert reverse_string("Hello, World! 123") == "321 !dlroW ,olleH"

def test_reverse_string_invalid_input():
"""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(["list"])