-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrunning_median.py
70 lines (66 loc) · 2.05 KB
/
running_median.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
from __future__ import division
import heapq
import time
"""
Problem: https://www.hackerrank.com/challenges/find-the-running-median/
"""
t = 10000#input()
min_heap = []
max_heap = []
heapq.heapify(min_heap)
heapq.heapify(max_heap)
max_heap_len = 0
min_heap_len = 0
ct = t
S = 0
# while ct:
with open('Median.txt') as mfile:
start = time.time()
for nelem in mfile:
if not ct:
break
n = int(nelem.strip())
if ct > t - 2:
if ct == t:
heapq.heappush(max_heap, -1*n)
max_heap_len += 1
#print "%.1f" % n
S += n
else:
if n < -1*max_heap[0]:
heapq.heappush(min_heap, -1*heapq.heappop(max_heap))
heapq.heappush(max_heap, -1*n)
else:
heapq.heappush(min_heap, n)
min_heap_len += 1
#print "%.1f" % ((-1*max_heap[0]+min_heap[0])/2)
S += ((-1*max_heap[0]+min_heap[0])/2)
ct -= 1
continue
if max_heap_len - min_heap_len > 0:
if n >= -1*max_heap[0]:
heapq.heappush(min_heap, n)
else:
heapq.heappush(min_heap, -1*heapq.heappop(max_heap))
heapq.heappush(max_heap, -1*n)
min_heap_len += 1
else:
if n <= min_heap[0]:
heapq.heappush(max_heap, -1*n)
else:
heapq.heappush(max_heap, -1*heapq.heappop(min_heap))
heapq.heappush(min_heap, n)
max_heap_len += 1
if (max_heap_len + min_heap_len) & 1:
if max_heap_len > min_heap_len:
#print "%.1f" % (-1*max_heap[0])
S += (-1*max_heap[0])
else:
#print "%.1f" % (min_heap[0])
S += (min_heap[0])
else:
#print "%.1f" % ((-1*max_heap[0] + min_heap[0])/2)
S += ((-1*max_heap[0] + min_heap[0])/2)
ct -= 1
print "%f seconds taken" %(time.time() - start)
print S%t