From 4bd8572fa512cc18568b1b339c18c675442aacb9 Mon Sep 17 00:00:00 2001 From: LeeTaek2T <137752192+LeeTaek2T@users.noreply.github.com> Date: Sun, 17 Mar 2024 00:46:58 +0900 Subject: [PATCH] Update priority_queue.py --- priority_queue.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/priority_queue.py b/priority_queue.py index 6aaf9e3..e335019 100644 --- a/priority_queue.py +++ b/priority_queue.py @@ -8,15 +8,17 @@ def push(self, item, priority): self._sift_up(len(self.heap) - 1) def pop(self): - if len(self.heap) > 1: - entry = self.heap.pop() - self._sift_down(0) - return entry[1] - elif len(self.heap) == 1: - entry = self.heap.pop() - return entry[1] + if self.heap: + if len(self.heap) > 1: + top_element = self.heap[0] + self.heap[0] = self.heap.pop() + self._sift_down(0) + return top_element[1] + else: + return self.heap.pop()[1] else: return None + def _sift_up(self, index): while index > 0: parent_index = (index - 1) // 2