@@ -62,10 +62,11 @@ def quick_select(items: list, index: int):
62
62
return quick_select (larger , index - (m + count ))
63
63
64
64
65
- def median (data : list ):
66
- """One common application of Quickselect is finding the median, which is
67
- the middle element (or average of the two middle elements) in a dataset. It
68
- works efficiently on unsorted lists by partially sorting the data without
65
+ def median (items : list ):
66
+ """
67
+ One common application of Quickselect is finding the median, which is
68
+ the middle element (or average of the two middle elements) in a sorted dataset.
69
+ It works efficiently on unsorted lists by partially sorting the data without
69
70
fully sorting the entire list.
70
71
71
72
>>> import random
@@ -80,14 +81,15 @@ def median(data: list):
80
81
81
82
>>> d = [2, 2, 3, 9, 9, 9]
82
83
>>> random.shuffle(d)
84
+ >>> d
85
+ [2, 2, 3, 9, 9, 9]
83
86
>>> median(d)
84
87
6.0
85
-
86
88
"""
87
- mid , rest = divmod (len (data ), 2 )
88
- if rest :
89
- return quick_select (data , mid )
89
+ mid , rest = divmod (len (items ), 2 )
90
+ if rest != 0 :
91
+ return quick_select (items = items , index = mid )
90
92
else :
91
- low_mid = quick_select (data , mid - 1 )
92
- high_mid = quick_select (data , mid )
93
+ low_mid = quick_select (items = items , index = mid - 1 )
94
+ high_mid = quick_select (items = items , index = mid )
93
95
return (low_mid + high_mid ) / 2
0 commit comments