@@ -37,18 +37,43 @@ def join(separator: str, separated: list[str]) -> str:
37
37
'apple-banana-cherry'
38
38
"""
39
39
40
- joined = ""
41
- for word_or_phrase in separated :
42
- if not isinstance (word_or_phrase , str ):
40
+ joined : str = ""
41
+ """
42
+ The last element of the list is not followed by the separator.
43
+ So, we need to iterate through the list and join each element
44
+ with the separator except the last element.
45
+ """
46
+ last_index : int = len (separated )- 1
47
+ """
48
+ Iterate through the list and join each element with the separator.
49
+ Except the last element, all other elements are followed by the separator.
50
+ """
51
+ for index in range (last_index ):
52
+ """
53
+ If the element is not a string, raise an exception.
54
+ """
55
+ if not isinstance ( separated [index ] ,str ):
43
56
raise Exception ("join() accepts only strings" )
44
- joined += word_or_phrase + separator
45
-
46
- # Remove the trailing separator
47
- # by stripping it from the result
48
- return joined .strip (separator )
57
+ """
58
+ join the element with the separator.
59
+ """
60
+ joined += separated [index ] + separator
61
+ """
62
+ If the list is not empty, join the last element.
63
+ """
64
+ if (separated != []) :
65
+ """
66
+ If the last element is not a string, raise an exception.
67
+ """
68
+ if not isinstance (separated [len (separated )- 1 ], str ):
69
+ raise Exception ("join() accepts only strings" )
70
+ joined += separated [len (separated )- 1 ]
71
+ """
72
+ RETURN the joined string.
73
+ """
74
+ return joined
49
75
50
76
51
77
if __name__ == "__main__" :
52
78
from doctest import testmod
53
-
54
79
testmod ()
0 commit comments