-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathheap.py
More file actions
82 lines (65 loc) · 2.2 KB
/
heap.py
File metadata and controls
82 lines (65 loc) · 2.2 KB
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
'''
A heap, similar to a binary tree,
but let's implement it using an array.
with an array, if node = array[2]
* left child will be array[2n]
* right child will be array[2n+1]
'''
from collections import Container
class Heap(Container):
array = []
# Allows "if item in tree:"
def __contains__(self, item):
return self._contains(item, 1)
def _contains(self, item, index):
if item > self.array[index-1]:
return False
elif item < self.array[index-1]:
if len(self.array) > index * 2:
return self._contains(item, index*2) or self._contains(item, index*2+1)
elif len(self.array) > index * 2 + 1:
return self._contains(item, index*2)
else:
return False
else:
return True
def add(self, item):
self.array.append(item)
self._bubble(len(self.array)-1)
def _bubble(self, index):
# Note: we take 1-based indexes, but convert them to 0-based ones
index = index-1
if self.array[index] > self.array[index/2]:
tmp = self.array[index]
self.array[index] = self.array[index/2]
self.array[index/2] = tmp
self._bubble(index/2)
# Useful for debugging. Prints the whole tree
def __repr__(self):
return self._repr(1)
def _repr(self, index, indent=0):
# Note: we use 1-based indexes here
string = ""
string = ('\t' * indent) + str(self.array[index-1]) + '\n'
if len(self.array) >= index * 2:
string += ('\t' * (indent+1)) + 'Left:\n'
string += self._repr(index*2, indent+1)
if len(self.array) >= index * 2 + 1:
string += ('\t' * (indent+1)) + 'Right:\n'
string += self._repr(index*2+1, indent+1)
return string
if __name__ == "__main__":
from random import randint
# Add random values
values = []
tree = Heap()
for i in range(10):
tree.add(i)
#values.append(val)
print(tree.array)
print(tree)
print("----" *20)
print(tree.array) # uses __repr__
#print(values)
#print(25 in tree) # uses __contains__
#print(25 in values)