We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a2fa32c commit 26ad689Copy full SHA for 26ad689
searches/quick_select.py
@@ -60,3 +60,25 @@ def quick_select(items: list, index: int):
60
# must be in larger
61
else:
62
return quick_select(larger, index - (m + count))
63
+
64
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
70
+ fully sorting the entire list.
71
72
+ >>> median([3, 2, 2, 9, 9])
73
+ 3
74
75
+ >>> median([2, 2, 9, 9, 9, 3])
76
+ 6.0
77
78
+ mid, rem = divmod(len(items), 2)
79
+ if rem != 0:
80
+ return quick_select(items=items, index=mid)
81
+ else:
82
+ low_mid = quick_select(items=items, index=mid - 1)
83
+ high_mid = quick_select(items=items, index=mid)
84
+ return (low_mid + high_mid) / 2
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments