|
1 |
| -""" |
2 |
| -Program to join a list of strings with a separator |
3 |
| -""" |
4 |
| - |
5 |
| - |
6 | 1 | def join(separator: str, separated: list[str]) -> str:
|
7 | 2 | """
|
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(). |
15 | 6 |
|
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. |
38 | 9 |
|
| 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. |
39 | 13 | """
|
40 |
| - |
41 | 14 | if not all(isinstance(word_or_phrase, str) for word_or_phrase in separated):
|
42 | 15 | raise Exception("join() accepts only strings")
|
43 | 16 |
|
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 |
45 | 23 |
|
46 |
| - return joined |
| 24 | + return result |
47 | 25 |
|
48 | 26 |
|
49 | 27 | if __name__ == "__main__":
|
|
0 commit comments