/
heap95.py
34 lines (32 loc) · 920 Bytes
/
heap95.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
# Copyright (c) 2012 Russell Heilling
# See LICENSE for details
import heapq
def percentile_sliced(tosort, percentile=95):
length = len(tosort)
heapmax = length - (length*percentile)//100
heap = tosort[:heapmax+1]
heapq.heapify(heap)
for item in tosort[heapmax+1:]:
if item > heap[0]:
heapq.heapreplace(heap, item)
if len(heap) < heapmax:
return 0
else:
return heap[0]
def percentile_simple(tosort, percentile=95):
length = len(tosort)
heapmax = length - (length*percentile)//100
heaplen = 0
heap = []
for item in tosort:
if heaplen < heapmax:
heap.append(item)
heaplen += 1
if heaplen == heapmax:
heapq.heapify(heap)
elif item > heap[0]:
heapq.heapreplace(heap, item)
if heaplen < heapmax:
return 0
else:
return heap[0]