1
1
"""
2
2
This is a pure Python implementation of the merge sort algorithm
3
-
4
3
For doctests run following command:
5
4
python -m doctest -v merge_sort.py
6
5
or
7
6
python3 -m doctest -v merge_sort.py
8
-
9
7
For manual testing run:
10
8
python merge_sort.py
11
9
"""
12
10
13
11
14
- def merge_sort (collection ) :
12
+ def merge_sort (collection : list ) -> list :
15
13
"""Pure implementation of the merge sort algorithm in Python
16
-
17
14
:param collection: some mutable ordered collection with heterogeneous
18
15
comparable items inside
19
16
:return: the same collection ordered by ascending
20
-
21
17
Examples:
22
18
>>> merge_sort([0, 5, 3, 2, 2])
23
19
[0, 2, 2, 3, 5]
24
-
25
20
>>> merge_sort([])
26
21
[]
27
-
28
22
>>> merge_sort([-2, -5, -45])
29
23
[-45, -5, -2]
30
24
"""
31
25
32
- def merge (left , right ) :
26
+ def merge (left : list , right : list ) -> list :
33
27
"""merge left and right
34
28
:param left: left collection
35
29
:param right: right collection
36
30
:return: merge result
37
31
"""
38
- result = []
39
- while left and right :
40
- result .append ((left if left [0 ] <= right [0 ] else right ).pop (0 ))
41
- return result + left + right
32
+ def _merge ():
33
+ while left and right :
34
+ yield (left if left [0 ] <= right [0 ] else right ).pop (0 )
35
+ yield from left
36
+ yield from right
37
+ return list (_merge ())
42
38
43
39
if len (collection ) <= 1 :
44
40
return collection
@@ -47,6 +43,8 @@ def merge(left, right):
47
43
48
44
49
45
if __name__ == "__main__" :
46
+ import doctest
47
+ doctest .testmod ()
50
48
user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
51
49
unsorted = [int (item ) for item in user_input .split ("," )]
52
50
print (* merge_sort (unsorted ), sep = "," )
0 commit comments