Fixed order of operations in Insert, added serialization and more unittests
This commit is contained in:
parent
2af96a1b4e
commit
38c099a94e
@ -89,12 +89,13 @@ class PriorityQueue:
|
|||||||
|
|
||||||
i = self.size
|
i = self.size
|
||||||
self.heap[i].set([entry])
|
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]:
|
while i > Literal(0) and self.heap[self.parent(i)].value[0] < self.heap[i].value[0]:
|
||||||
self.swap(i, self.parent(i))
|
self.swap(i, self.parent(i))
|
||||||
i = self.parent(i)
|
i = self.parent(i)
|
||||||
|
|
||||||
|
self.size += Literal(1)
|
||||||
|
|
||||||
def pop(self):
|
def pop(self):
|
||||||
if self.isEmpty():
|
if self.isEmpty():
|
||||||
raise IndexError("Queue is empty!")
|
raise IndexError("Queue is empty!")
|
||||||
@ -119,6 +120,36 @@ class PriorityQueue:
|
|||||||
def __len__(self):
|
def __len__(self):
|
||||||
return self.size
|
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__':
|
if __name__ == '__main__':
|
||||||
# Proof of Concept
|
# Proof of Concept
|
||||||
@ -153,6 +184,11 @@ if __name__ == '__main__':
|
|||||||
pq.insert(HeapEntry("A", 1))
|
pq.insert(HeapEntry("A", 1))
|
||||||
pq.insert(HeapEntry("C", 3))
|
pq.insert(HeapEntry("C", 3))
|
||||||
pq.insert(HeapEntry("B", 2))
|
pq.insert(HeapEntry("B", 2))
|
||||||
|
pq.insert(HeapEntry(42, 4))
|
||||||
|
pq.insert(HeapEntry(42, 1))
|
||||||
|
pq.insert(HeapEntry("C", 2))
|
||||||
|
print(pq)
|
||||||
|
while not pq.isEmpty():
|
||||||
print(pq.pop())
|
print(pq.pop())
|
||||||
print(pq.pop())
|
|
||||||
print(pq.pop())
|
testQueueRandom(100)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user