Question: Python Help. Right now I am trying to find an error in my code. I am not able to find the error in my code.
Python Help. Right now I am trying to find an error in my code. I am not able to find the error in my code. My upheap function does not work. I am unable to correctly position node with upheap.
class PriorityQueue: def __init__(self, entries=None, key=lambda x: x): self._entries = list(entries or []) self.key = key self._heapify()
def insert(self, item): self._entries.append(item) self._upheap(len(self))
def _parent(self, i): return (i - 1) // 2
def _children(self, i): left, right = 2 * i + 1, 2 * i + 2 return range(left, min(len(self), right + 1)) def findtop(self): try: return self._entries[0] except: return None
def removetop(self): L = self._entries if len(L) == 0: return None self._swap(0, len(L) - 1) item = L.pop() self._downheap(0) return item
def _swap(self, a, b): L = self._entries L[a], L[b] = L[b], L[a]
# implement this method def _upheap(self, i): L=self._entries parent=self._parent(i) print(L[i]) print(L[parent]) s=min(L[parent],L[i], key=self.key) if i>0 and L[i] self._swap(i,parent) self._upheap(parent) pass # implement this method def _downheap(self, i): L=self._entries children=self._children(i) if children: child=min(children, key=lambda x:L[x]) if L[child] self._swap(i,child) self._downheap(child) pass
def __len__(self): return len(self._entries)
def _heapify(self): for i in range(len(self)): self._downheap(len(self) - i - 1) # implement this method def update(self, other): self._entries.extend(other._entries) self._heapify() pass # implement this method def _isheap(self): return all(self._entries[i] >= self._entries[(i - 1) // 2] for i in range(1, len(self._entries))) pass
if __name__ == '__main__': ent = [[10, 'p', 100], [1, 'q', 10], [10, 's', 99], [1, 'r', 1],[2, 'x', 6], [2, 't', 33], [10, 'z', 1000], [1000, 'w', 2]] solution = [[100, 'c', 100], [10, 'p', 100], [10, 's', 99], [1, 'q', 10],[2, 'x', 6], [2, 't', 33], [10, 'z', 1000], [1000, 'w', 2], [1, 'r', 1]] pq = PriorityQueue(ent, lambda x:x[1]) print(pq._entries) pq._entries.append([100, 'c', 100]) pq._upheap(8) print(pq._entries)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
