【问题标题】:How can I avoid Runtime error while implementing Heap Data Structure?实现堆数据结构时如何避免运行时错误?
【发布时间】:2018-03-30 13:25:57
【问题描述】:

我正在尝试在 HackerRank 中使用 python 解决堆数据结构问题。
我通过两种方式实现它

第一个

from heapq import heappush,heappop

heap = []
deleted_nodes = []
num_of_entries = int(input())

for i in range(num_of_entries):

    line = list(map(int, input().strip().split(' ')))
    if line[0] == 1:
        heappush(heap,line[1])
    elif line[0] == 2:
        if heap[0] == line[1]:
            heappop(heap)
        else:
            heappush(deleted_nodes,line[1])

    elif line[0] == 3:
        check = bool(deleted_nodes)
        while check:
            if deleted_nodes[0] == heap[0]:
                heappop(heap)
                heappop(deleted_nodes)
                check = bool(deleted_nodes)
            else:
                check = False
                print(heap[0])

第二个

from heapq import heappush,heappop


class Heap:
    def __init__(self):
        self.heap = []
        self.deleted_nodes = []

    def delete(self,value):
        if self.heap[0] == value:
            heappop(self.heap)
        else:
            heappush(self.deleted_nodes,value)

    def get_min(self):
        check = bool(self.deleted_nodes)
        while check:
            if self.deleted_nodes[0] == self.heap[0]:
                heappop(self.heap)
                heappop(self.deleted_nodes)
                check = bool(self.deleted_nodes)
            else:
                check = False
        print(self.heap[0])


if __name__ == "__main__":

    heap = Heap()
    num_of_entries = int(input())

    for i in range(num_of_entries):

        line = input().strip().split(' ')
        line = list(map(int,line))
        if line[0] == 1:
            heappush(heap.heap,line[1])

        elif line[0] == 2:
            heap.delete(line[1])

        elif line[0] == 3:
            heap.get_min()

第一个成功通过了所有测试用例。

第二个通过了超过一半的测试用例,其余部分不断出现运行时错误

我真的不明白为什么会这样。

PS:大多数失败的测试用例包含超过 10000 个值

【问题讨论】:

  • 您是否使用失败的测试用例自己运行程序,并看到它失败?看来这应该是你做的第一件事。然后你可以看到 where 它失败了,以及具体的运行时错误是什么。如果您无权访问失败的测试用例,请自己创建一个。
  • 似乎用 input() 进行输入会导致运行时错误。也许我应该在未来开始使用标准输入优化我的代码。

标签: python python-3.x data-structures heap priority-queue


【解决方案1】:

看起来我应该通过

stdin.readlines()

我替换了几行,它确实通过了所有测试用例。

if __name__ == "__main__":
    heap = Heap()
    lines = stdin.readlines()
    for line in lines[1:]:
        line = line.split()
        line = list(map(int,line))
        if line[0] == 1:
            heappush(heap.heap,line[1])
        elif line[0] == 2:
            heap.delete(line[1])
        elif line[0] == 3:
            heap.get_min()

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2021-10-11
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    相关资源
    最近更新 更多