forked from yendelevium/DSA-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Minheap.py
83 lines (64 loc) · 2.77 KB
/
Minheap.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
from seeds import getGames # Import the getGames function to retrieve games list
from ADT import Game # Import Game to confirm we are working with Game objects
class MinHeap:
def __init__(self, priority_field="price"):#setting default priority as price
self.heap = []
self.priority_field = priority_field
def parent(self, index):
return (index - 1) // 2
def leftChild(self, index):
return 2 * index + 1
def rightChild(self, index):
return 2 * index + 2
def hasParent(self, index):
return self.parent(index) >= 0
def hasLeftChild(self, index):
return self.leftChild(index) < len(self.heap)
def hasRightChild(self, index):
return self.rightChild(index) < len(self.heap)
def swap(self, index1, index2):
self.heap[index1], self.heap[index2] = self.heap[index2], self.heap[index1]
def peek(self):
if not self.heap:
return None
return self.heap[0]
def insert(self, game):
self.heap.append(game)
self.heapifyUp(len(self.heap) - 1)
def heapifyUp(self, index):
while (self.hasParent(index) and
self.getPriorityValue(self.parent(index)) > self.getPriorityValue(index)):
self.swap(self.parent(index), index)
index = self.parent(index)
def heapifyDown(self, index):
while self.hasLeftChild(index):
smaller_child_index = self.leftChild(index)
if (self.hasRightChild(index) and
self.getPriorityValue(self.rightChild(index)) < self.getPriorityValue(smaller_child_index)):
smaller_child_index = self.rightChild(index)
if self.getPriorityValue(index) <= self.getPriorityValue(smaller_child_index):
break # Heap property is satisfied
else:
self.swap(index, smaller_child_index)
index = smaller_child_index
def extractMin(self):
if not self.heap:
return None
if len(self.heap) == 1:
return self.heap.pop()
root = self.heap[0]
self.heap[0] = self.heap.pop() # Move the last element to the root
self.heapifyDown(0) # Maintain the heap property
return root
def getPriorityValue(self, index):
return getattr(self.heap[index], self.priority_field)
def importGames(self):
games = getGames() # Get the list of games from the seeds module
for game in games:
self.insert(game)
def extractSortedGames(self):
sorted_games = []
while self.heap and len(sorted_games) < 10: # Only extract up to 10 games
game = self.extractMin()
sorted_games.append(game)
return sorted_games # Return list of Game objects directly