From 38c099a94ec407cc6138f40439cb9cebddd693c3 Mon Sep 17 00:00:00 2001 From: schoeffelbe82781 Date: Sun, 13 Apr 2025 19:04:22 +0200 Subject: [PATCH] Fixed order of operations in Insert, added serialization and more unittests --- schoeffelbe/priorityQueue.py | 44 ++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/schoeffelbe/priorityQueue.py b/schoeffelbe/priorityQueue.py index c5fb212..ca1541a 100644 --- a/schoeffelbe/priorityQueue.py +++ b/schoeffelbe/priorityQueue.py @@ -89,11 +89,12 @@ class PriorityQueue: i = self.size self.heap[i].set([entry]) - self.size += Literal(1) while i > Literal(0) and self.heap[self.parent(i)].value[0] < self.heap[i].value[0]: self.swap(i, self.parent(i)) i = self.parent(i) + + self.size += Literal(1) def pop(self): if self.isEmpty(): @@ -119,6 +120,36 @@ class PriorityQueue: def __len__(self): return self.size + def __str__(self): + entries = [] + for i in mrange(self.size.value): + entry = self.heap[i].value[0] + if entry.getItem() != MAX_VALUE: + entries.append(str(entry)) + return "[" + ", ".join(entries) + "]" + +def testQueueRandom(number: int): + import random + import string + + pq = PriorityQueue(Literal(101)) + + entries = [] + for _ in range(number): + value = ''.join(random.choices(string.ascii_uppercase + string.digits, k=3)) + priority = random.randint(1, 100) + entry = HeapEntry(value, priority) + entries.append(entry) + pq.insert(entry) + + print(pq) + for entry in entries: + print(entry) + + while not pq.isEmpty(): + print(pq.pop()) + + if __name__ == '__main__': # Proof of Concept @@ -153,6 +184,11 @@ if __name__ == '__main__': pq.insert(HeapEntry("A", 1)) pq.insert(HeapEntry("C", 3)) pq.insert(HeapEntry("B", 2)) - print(pq.pop()) - print(pq.pop()) - print(pq.pop()) + pq.insert(HeapEntry(42, 4)) + pq.insert(HeapEntry(42, 1)) + pq.insert(HeapEntry("C", 2)) + print(pq) + while not pq.isEmpty(): + print(pq.pop()) + + testQueueRandom(100)