Skip to content

Commit ffca780

Browse files
committed
feat: Add reverse_string_builtin()
1 parent 7ae3d39 commit ffca780

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/basic/string.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,27 @@ def reverse_string(text: str) -> str:
2020
return text[::-1]
2121

2222

23+
def reverse_string_builtin(text: str) -> str:
24+
"""
25+
Returns the reversed string using Python's built-in reversed() function
26+
27+
Args:
28+
text (str): The string to be reversed
29+
30+
Returns:
31+
str: The reversed string
32+
33+
Examples:
34+
>>> reverse_string_builtin("hello")
35+
'olleh'
36+
"""
37+
# reversed(sequence): creates an iterator that yields elements in reverse order
38+
# (works with sequences like str, list, tuple, but not with unordered iterables like set)
39+
# "".join(): concatenates iterator elements into a single string using empty string as separator
40+
# example: "hello" -> iterator('o','l','l','e','h') -> "olleh"
41+
return "".join(reversed(text))
42+
43+
2344
def extract_alphanumeric(s: str) -> str:
2445
"""
2546
Extracts only alphanumeric characters from the given string

test/basic/test_string.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44

55
import unittest
66

7-
from src.basic.string import extract_alphanumeric, reverse_string
7+
from src.basic.string import (
8+
extract_alphanumeric,
9+
reverse_string,
10+
reverse_string_builtin,
11+
)
812

913

1014
class TestString(unittest.TestCase):
@@ -31,6 +35,27 @@ def test_reverse_string_with_spaces(self):
3135
"""Test for string with spaces"""
3236
self.assertEqual(reverse_string("hello world"), "dlrow olleh")
3337

38+
def test_reverse_string_builtin_basic(self):
39+
"""Test for basic string reversal using built-in function"""
40+
self.assertEqual(reverse_string_builtin("hello"), "olleh")
41+
self.assertEqual(reverse_string_builtin("python"), "nohtyp")
42+
43+
def test_reverse_string_builtin_empty(self):
44+
"""Test for empty string using built-in function"""
45+
self.assertEqual(reverse_string_builtin(""), "")
46+
47+
def test_reverse_string_builtin_single_char(self):
48+
"""Test for single character string using built-in function"""
49+
self.assertEqual(reverse_string_builtin("a"), "a")
50+
51+
def test_reverse_string_builtin_japanese(self):
52+
"""Test for Japanese string using built-in function"""
53+
self.assertEqual(reverse_string_builtin("こんにちは"), "はちにんこ")
54+
55+
def test_reverse_string_builtin_with_spaces(self):
56+
"""Test for string with spaces using built-in function"""
57+
self.assertEqual(reverse_string_builtin("hello world"), "dlrow olleh")
58+
3459
def test_extract_alphanumeric_basic(self):
3560
"""Test for basic alphanumeric extraction"""
3661
self.assertEqual(extract_alphanumeric("Hello123"), "Hello123")

0 commit comments

Comments
 (0)