forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjoin.py
74 lines (59 loc) · 2.01 KB
/
join.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
Program to join a list of strings with a separator
"""
defjoin(separator: str, separated: list[str]) ->str:
"""
Joins a list of strings using a separator
and returns the result.
:param separator: Separator to be used
for joining the strings.
:param separated: List of strings to be joined.
:return: Joined string with the specified separator.
Examples:
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join(",", ["", "", ""])
',,'
This example should raise an
exception for non-string elements:
>>> join("#", ["a", "b", "c", 1])
Traceback (most recent call last):
...
Exception: join() accepts only strings
Additional test case with a different separator:
>>> join("-", ["apple", "banana", "cherry"])
'apple-banana-cherry'
"""
# Check that all elements are strings
forword_or_phraseinseparated:
# If the element is not a string, raise an exception
ifnotisinstance(word_or_phrase, str):
raiseException("join() accepts only strings")
joined: str=""
"""
The last element of the list is not followed by the separator.
So, we need to iterate through the list and join each element
with the separator except the last element.
"""
last_index: int=len(separated) -1
"""
Iterate through the list and join each element with the separator.
Except the last element, all other elements are followed by the separator.
"""
forword_or_phraseinseparated[:last_index]:
# join the element with the separator.
joined+=word_or_phrase+separator
# If the list is not empty, join the last element.
ifseparated!= []:
joined+=separated[last_index]
# Return the joined string.
returnjoined
if__name__=="__main__":
fromdoctestimporttestmod
testmod()