mirror of
https://github.com/donnemartin/interactive-coding-challenges.git
synced 2024-03-22 13:11:13 +08:00
41 lines
931 B
Python
41 lines
931 B
Python
import sys
|
|
|
|
|
|
class PriorityQueueNode(object):
|
|
|
|
def __init__(self, obj, key):
|
|
self.obj = obj
|
|
self.key = key
|
|
|
|
def __repr__(self):
|
|
return str(self.obj) + ': ' + str(self.key)
|
|
|
|
|
|
class PriorityQueue(object):
|
|
|
|
def __init__(self):
|
|
self.array = []
|
|
|
|
def __len__(self):
|
|
return len(self.array)
|
|
|
|
def insert(self, node):
|
|
self.array.append(node)
|
|
return self.array[-1]
|
|
|
|
def extract_min(self):
|
|
if not self.array:
|
|
return None
|
|
minimum = sys.maxsize
|
|
for index, node in enumerate(self.array):
|
|
if node.key < minimum:
|
|
minimum = node.key
|
|
minimum_index = index
|
|
return self.array.pop(minimum_index)
|
|
|
|
def decrease_key(self, obj, new_key):
|
|
for node in self.array:
|
|
if node.obj is obj:
|
|
node.key = new_key
|
|
return node
|
|
return None |