-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHeap.py
360 lines (284 loc) · 11 KB
/
Heap.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import math
from io import StringIO
class MinHeap(object):
heap = [] # heap list
check_flag = False # True for running the checking code
def __init__(self, unsorted_list: list, check_flag=False):
self.heap = unsorted_list
self.check_flag = check_flag
# heapify the unsorted list
self.heapify()
def __swap(self, index1, index2):
self.heap[index1], self.heap[index2] = self.heap[index2], self.heap[index1]
def __bubble_up(self):
# i is the tail index of the list
i = len(self.heap) - 1
while i != 0:
# if the child node smaller than parent node, swap them
if self.heap[(i + 1) // 2 - 1] > self.heap[i]:
self.__swap((i + 1) // 2 - 1, i)
i = (i + 1) // 2 - 1
else:
break
def __bubble_down(self, index: int = 0):
# if there is no input value, then bubble down from top
while True:
# in this case, the node has two children
try:
# decide with which child to swap, if necessary
if self.heap[2 * (index + 1) - 1] < self.heap[2 * (index + 1)]:
if self.heap[index] > self.heap[2 * (index + 1) - 1]:
self.__swap(index, 2 * (index + 1) - 1)
index = 2 * (index + 1) - 1
else:
break
else:
if self.heap[index] > self.heap[2 * (index + 1)]:
self.__swap(index, 2 * (index + 1))
index = 2 * (index + 1)
else:
break
# in this case, the node has only one child
except IndexError:
try:
if self.heap[index] > self.heap[2 * (index + 1) - 1]:
self.__swap(index, 2 * (index + 1) - 1)
index = 2 * (index + 1) - 1
else:
break
# in this case, the node has no children, stop the procedure
except IndexError:
break
def check(self):
"""
Check if the heap is still balance.
"""
if self.check_flag:
for i in range(1, len(self.heap)):
if self.heap[(i + 1) // 2 - 1] > self.heap[i]:
print('-----Error List-----')
print(self.heap)
print('-----Error Value-----')
print('{} : {}'.format(self.heap[(i + 1) // 2 - 1], self.heap[i]))
raise ValueError('Heap Error!')
def heapify(self):
"""
Heapify the heap to reach a balance.
"""
original_heap = self.heap
self.heap = []
for i in range(len(original_heap)):
# add the next entry into heap
self.heap.append(original_heap[i])
self.__bubble_up()
self.check()
def push(self, value):
"""
Push a value into the heap and rebalance the tree.
Args:
value: input value for pushing
"""
# add the new value to the tail of the list
self.heap.append(value)
# bubble up to update the heap
self.__bubble_up()
self.check()
def pop(self):
"""
Pop the minimum of the heap, and rebalance the tree.
Returns:
min_value: the minimum of the heap
"""
# swap the first value and the last value
self.__swap(0, -1)
# pop the list to get the minimum for later return
min_value = self.heap.pop()
# bubble down to update the heap
self.__bubble_down()
self.check()
return min_value
def delete(self, value):
"""
Delete the certain value in the heap, and rebalance the tree.
Args:
value: input value to be deleted
"""
delete_complete = False
# find the index of value and delete it from the heap
for i in range(len(self.heap)):
if value == self.heap[i]:
self.__swap(i, -1)
self.heap.pop()
delete_complete = True
# if the value is the last value of the heap, no need for heapify or bubble down
if i == len(self.heap):
break
# if the swapped value breaks the balance, heapify again
if self.heap[(i + 1) // 2 - 1] > self.heap[i]:
self.heapify()
else:
self.__bubble_down(i)
break
if not delete_complete:
print("No such value in the heap!")
def show_tree(self, total_width=36, fill=' '):
"""
Draw a tree, from learnku.com - heapq
"""
output = StringIO()
last_row = -1
for i, n in enumerate(self.heap):
if i:
row = int(math.floor(math.log(i + 1, 2)))
else:
row = 0
if row != last_row:
output.write('\n')
columns = 2 ** row
col_width = int(math.floor(total_width / columns))
output.write(str(n).center(col_width, fill))
last_row = row
print(output.getvalue())
print('-' * total_width)
print()
class MaxHeap(object):
heap = [] # heap list
check_flag = False # True for running the checking code
def __init__(self, unsorted_list: list, check_flag=False):
self.heap = unsorted_list
self.check_flag = check_flag
# heapify the unsorted list
self.heapify()
def __swap(self, index1, index2):
self.heap[index1], self.heap[index2] = self.heap[index2], self.heap[index1]
def __bubble_up(self):
# i is the tail index of the list
i = len(self.heap) - 1
while i != 0:
# if the child node bigger than parent node, swap them
if self.heap[(i + 1) // 2 - 1] < self.heap[i]:
self.__swap((i + 1) // 2 - 1, i)
i = (i + 1) // 2 - 1
else:
break
def __bubble_down(self, index: int = 0):
# if there is no input value, then bubble down from top
while True:
# in this case, the node has two children
try:
# decide with which child to swap, if necessary
if self.heap[2 * (index + 1) - 1] > self.heap[2 * (index + 1)]:
if self.heap[index] < self.heap[2 * (index + 1) - 1]:
self.__swap(index, 2 * (index + 1) - 1)
index = 2 * (index + 1) - 1
else:
break
else:
if self.heap[index] < self.heap[2 * (index + 1)]:
self.__swap(index, 2 * (index + 1))
index = 2 * (index + 1)
else:
break
# in this case, the node has only one child
except IndexError:
try:
if self.heap[index] < self.heap[2 * (index + 1) - 1]:
self.__swap(index, 2 * (index + 1) - 1)
index = 2 * (index + 1) - 1
else:
break
# in this case, the node has no children, stop the procedure
except IndexError:
break
def check(self):
"""
Check if the heap is still balance.
"""
if self.check_flag:
for i in range(1, len(self.heap)):
if self.heap[(i + 1) // 2 - 1] < self.heap[i]:
print('-----Error List-----')
print(self.heap)
print('-----Error Value-----')
print('{} : {}'.format(self.heap[(i + 1) // 2 - 1], self.heap[i]))
raise ValueError('Heap Error!')
def heapify(self):
"""
Heapify the heap to reach a balance.
"""
original_heap = self.heap
self.heap = []
for i in range(len(original_heap)):
# add the next entry into heap
self.heap.append(original_heap[i])
self.__bubble_up()
self.check()
def push(self, value):
"""
Push a value into the heap and rebalance the tree.
Args:
value: input value for pushing
"""
# add the new value to the tail of the list
self.heap.append(value)
# bubble up to update the heap
self.__bubble_up()
self.check()
def pop(self):
"""
Pop the minimum of the heap, and rebalance the tree.
Returns:
max_value: the minimum of the heap
"""
# swap the first value and the last value
self.__swap(0, -1)
# pop the list to get the minimum for later return
max_value = self.heap.pop()
# bubble down to update the heap
self.__bubble_down()
self.check()
return max_value
def delete(self, value):
"""
Delete the certain value in the heap, and rebalance the tree.
Args:
value: input value to be deleted
"""
delete_complete = False
# find the index of value and delete it from the heap
for i in range(len(self.heap)):
if value == self.heap[i]:
self.__swap(i, -1)
self.heap.pop()
delete_complete = True
# if the value is the last value of the heap, no need for heapify or bubble down
if i == len(self.heap):
break
# if the swapped value breaks the balance, heapify again
if self.heap[(i + 1) // 2 - 1] < self.heap[i]:
self.heapify()
else:
self.__bubble_down(i)
break
if not delete_complete:
print("No such value in the heap!")
def show_tree(self, total_width=36, fill=' '):
"""
Draw a tree, from learnku.com - heapq
"""
output = StringIO()
last_row = -1
for i, n in enumerate(self.heap):
if i:
row = int(math.floor(math.log(i + 1, 2)))
else:
row = 0
if row != last_row:
output.write('\n')
columns = 2 ** row
col_width = int(math.floor(total_width / columns))
output.write(str(n).center(col_width, fill))
last_row = row
print(output.getvalue())
print('-' * total_width)
print()