@@ -27,10 +27,13 @@ class MinHeap:
2727 >>> myMinHeap.decrease_key(b, -17)
2828 >>> print(b)
2929 Node(B, -17)
30+ >>> print(myMinHeap.get_value("B"))
31+ -17
3032 """
3133
3234 def __init__ (self , array ):
3335 self .idx_of_element = {}
36+ self .heap_dict = {}
3437 self .heap = self .build_heap (array )
3538
3639 def get_parent_idx (self , idx ):
@@ -42,12 +45,16 @@ def get_left_child_idx(self, idx):
4245 def get_right_child_idx (self , idx ):
4346 return idx * 2 + 2
4447
48+ def get_value (self , key ):
49+ return self .heap_dict [key ]
50+
4551 def build_heap (self , array ):
4652 lastIdx = len (array ) - 1
4753 startFrom = self .get_parent_idx (lastIdx )
4854
4955 for idx , i in enumerate (array ):
5056 self .idx_of_element [i ] = idx
57+ self .heap_dict [i .name ] = i .val
5158
5259 for i in range (startFrom , - 1 , - 1 ):
5360 self .sift_down (i , array )
@@ -103,20 +110,22 @@ def remove(self):
103110 self .sift_down (0 , self .heap )
104111 return x
105112
106- def insert (self , value ):
107- self .heap .append (value )
108- self .idx_of_element [value ] = len (self .heap ) - 1
113+ def insert (self , node ):
114+ self .heap .append (node )
115+ self .idx_of_element [node ] = len (self .heap ) - 1
116+ self .heap_dict [node .name ] = node .val
109117 self .sift_up (len (self .heap ) - 1 )
110118
111119 def is_empty (self ):
112120 return True if len (self .heap ) == 0 else False
113121
114- def decrease_key (self , key , newValue ):
122+ def decrease_key (self , node , newValue ):
115123 assert (
116- self .heap [self .idx_of_element [key ]].val > newValue
124+ self .heap [self .idx_of_element [node ]].val > newValue
117125 ), "newValue must be less that current value"
118- key .val = newValue
119- self .sift_up (self .idx_of_element [key ])
126+ node .val = newValue
127+ self .heap_dict [node .name ] = newValue
128+ self .sift_up (self .idx_of_element [node ])
120129
121130
122131## USAGE
@@ -151,7 +160,6 @@ def decrease_key(self, key, newValue):
151160for i in myMinHeap .heap :
152161 print (i )
153162
154-
155163if __name__ == "__main__" :
156164 import doctest
157165
0 commit comments