generated from pykit3/tmpl
-
Notifications
You must be signed in to change notification settings - Fork 3
/
refheap.py
292 lines (198 loc) · 6.25 KB
/
refheap.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# index is started from 1.
#
# 1
# 2 3
# 4 5 6 7
# level
# 1 0
# 10 11 1
# 100 101 110 111 2
#
# - On each level, widths of level in binary number are the same and just equals level+1.
# - The most significant bit are always 1.
# - The 2nd significant bit indicate it is on left(0) or right(1) level-1 sub-heap.
# - The 3rd significant bit indicate it is on left(0) or right(1) level-2 sub-heap.
# - ...
primitive_types = (type(None), int, bool, str, tuple, float, complex)
class HeapError(Exception):
pass
class Duplicate(HeapError):
pass
class Empty(HeapError):
pass
class NotFound(HeapError):
pass
class Node(list):
# node in heap:
# node[0] is left child
# node[1] is right child
def __init__(self, userdata):
super(Node, self).__init__([None, None])
self.parent = None
self.userdata = userdata
def min_child(self):
if self[0] is None:
return self[1]
if self[1] is None:
return self[0]
if self[0].userdata < self[1].userdata:
return self[0]
else:
return self[1]
def __lt__(self, b):
return self.userdata < b.userdata
def __str__(self):
ud_str = str(self.userdata)
mark = '> '
width = 16
item_width = width + len(mark)
ud_str = ('{0:>' + str(width) + '}').format(ud_str)
ud_str = ud_str + mark
if self == [None, None]:
return ud_str
if self[0] is None:
sl = ['-']
else:
sl = str(self[0]).split('\n')
if self[1] is None:
sr = ['-']
else:
sr = str(self[1]).split('\n')
sl = [' ' * item_width + x for x in sl]
sr = [' ' * item_width + x for x in sr]
sl[0] = ud_str + sl[0][item_width:]
return '\n'.join(sl) + '\n' + '\n'.join(sr)
# wrapper of primitive type
class Primitive(object):
def __init__(self, obj):
self.data = obj
def __str__(self):
return str(self.data)
def __lt__(self, b):
return self.data < b.data
class RefHeap(object):
def __init__(self, iterable=()):
self.size = 0
self.root = None
# map user data `obj` to heap node instance.
self.userdata_map = {}
for i in iterable:
self.push(i)
def push(self, obj):
# wrap primitive type with an object or no duplicate can be added
if isinstance(obj, primitive_types):
obj = Primitive(obj)
obj_id = id(obj)
if obj_id in self.userdata_map:
raise Duplicate('object is already in heap')
node = Node(obj)
self.userdata_map[obj_id] = node
self.size += 1
if self.size == 1:
self.root = node
return
pos = self.size
p = self.node_at(_parent_index(pos))
p[_child_lr_idx(pos)] = node
node.parent = p
self._sift(node)
def get(self):
self.assert_not_empty()
return self.return_val(self.root)
def pop(self):
self.assert_not_empty()
return self.remove_node(self.root)
def pop_all(self, map=lambda x: x):
rst = []
while self.size > 0:
rst.append(map(self.pop()))
return rst
def remove(self, obj):
node = self._get_object_node(obj)
return self.remove_node(node)
def remove_node(self, node):
rst = self.return_val(node)
last = self.node_at(self.size)
self.swap(node, last)
self.remove_last(last)
self._sift(node)
if self.size == 0:
self.root = None
return rst
def sift(self, obj):
if isinstance(obj, primitive_types):
raise ValueError('primitive type does not support sift, just replace it')
node = self._get_object_node(obj)
return self._sift(node)
def _get_object_node(self, obj):
if id(obj) not in self.userdata_map:
raise NotFound('object is not found in heap, id:' + str(obj))
node = self.userdata_map[id(obj)]
return node
def _sift(self, node):
x = node.userdata
xid = id(x)
# upwards
up = False
while (node.parent is not None
and x < node.parent.userdata):
# move parent down to node
self.userdata_map[id(node.parent.userdata)] = node
node.userdata = node.parent.userdata
node = node.parent
up = True
node.userdata = x
self.userdata_map[xid] = node
if up:
return
# downwards
while True:
_min = node.min_child()
if _min is None or not (_min.userdata < x):
break
# move _min up to node
self.userdata_map[id(_min.userdata)] = node
node.userdata = _min.userdata
node = _min
node.userdata = x
self.userdata_map[xid] = node
def swap(self, a, b):
# we do not swap node, but exchange node.userdata only.
self.userdata_map[id(a.userdata)], self.userdata_map[id(b.userdata)] = b, a
a.userdata, b.userdata = b.userdata, a.userdata
def remove_last(self, last):
if last.parent is not None:
last.parent[_child_lr_idx(self.size)] = None
last.parent = None
del self.userdata_map[id(last.userdata)]
last.userdata = None
self.size -= 1
def return_val(self, node):
rst = node.userdata
if isinstance(rst, Primitive):
rst = rst.data
return rst
def node_at(self, idx):
# idx starts from 1
p = self.root
lvl = index_level(idx)
for l in range(lvl - 1, -1, -1):
lr = (idx >> l) & 1
p = p[lr]
return p
def assert_not_empty(self):
if self.size == 0:
raise Empty()
def __str__(self):
return str(self.root)
def index_level(idx):
# root is at level 0
lvl = 0
while idx > 1:
idx = _parent_index(idx)
lvl += 1
return lvl
def _parent_index(c):
return c // 2
def _child_lr_idx(idx):
return idx % 2