Skip to content

Commit 0b45a6d

Browse files
committed
Custom Implementation of join.py
1 parent de9aa38 commit 0b45a6d

File tree

1 file changed

+15
-37
lines changed

1 file changed

+15
-37
lines changed

strings/join.py

+15-37
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,27 @@
1-
"""
2-
Program to join a list of strings with a separator
3-
"""
4-
5-
61
def join(separator: str, separated: list[str]) -> str:
72
"""
8-
Joins a list of strings using a separator
9-
and returns the result.
10-
11-
:param separator: Separator to be used for joining the strings.
12-
:param separated: List of strings to be joined.
13-
14-
:return: Joined string with the specified separator.
3+
Custom implementation of the join() function.
4+
This function manually concatenates the strings in the list,
5+
using the provided separator, without relying on str.join().
156
16-
Examples:
17-
18-
>>> join("", ["a", "b", "c", "d"])
19-
'abcd'
20-
>>> join("#", ["a", "b", "c", "d"])
21-
'a#b#c#d'
22-
>>> join("#", ["a"])
23-
'a'
24-
>>> join(" ", ["You", "are", "amazing!"])
25-
'You are amazing!'
26-
27-
This example should raise an exception for non-string elements:
28-
>>> join("#", ["a", "b", "c", 1])
29-
Traceback (most recent call last):
30-
...
31-
Exception: join() accepts only strings
32-
33-
Additional test case with a different separator:
34-
>>> join("-", ["apple", "banana", "cherry"])
35-
'apple-banana-cherry'
36-
>>> join(",", ["", "", ""])
37-
',,,' # This test will now pass correctly
7+
:param separator: The separator to place between strings.
8+
:param separated: A list of strings to join.
389
10+
:return: A single string with elements joined by the separator.
11+
12+
:raises Exception: If any element in the list is not a string.
3913
"""
40-
4114
if not all(isinstance(word_or_phrase, str) for word_or_phrase in separated):
4215
raise Exception("join() accepts only strings")
4316

44-
joined = separator.join(separated)
17+
# Manually handle concatenation
18+
result = ""
19+
for i, element in enumerate(separated):
20+
result += element
21+
if i < len(separated) - 1: # Add separator only between elements
22+
result += separator
4523

46-
return joined
24+
return result
4725

4826

4927
if __name__ == "__main__":

0 commit comments

Comments
 (0)