【问题标题】:TypeError: '<' not supported between instances of 'HeapNode' and 'HeapNode'TypeError:“HeapNode”和“HeapNode”的实例之间不支持“<”
【发布时间】:2018-06-03 08:52:14
【问题描述】:

当我尝试将一个节点推送到哈夫曼树的堆上时,我收到此错误:

TypeError: 'HeapNode' 和 'HeapNode' 的实例之间不支持'

    class HuffmanCoding:
        def __init__(self, path):
            self.path = path
            self.heap = []
            self.codes = {}
            self.reverse_mapping = {}

        def make_heap(self, frequency):
            for key in frequency:
                node = HeapNode(key, frequency[key])
                heapq.heappush(self.heap, node)

节点类:

    class HeapNode:
        def __init__(self, char, freq):
            self.char = char
            self.freq = freq
            self.left = None
            self.right = None

        def __cmp__(self, other):
            if(other == None):
                return -1
            if(not isinstance(other, HeapNode)):
                return -1
            return self.freq > other.freq

错误是由以下原因引起的:

    heapq.heappush(self.heap, node)

Full code by github.com/bhrigu123

【问题讨论】:

  • 看起来HeapNode 不支持排序(它没有__lt____eq__ 等方法)
  • 我相信@mgilson 是正确的。您需要重载比较运算符。还有,好听的名字。
  • 您尝试在两个堆节点上调用 operator &lt;,但您从未定义过这样的方法。

标签: python python-3.x heap nodes huffman-code


【解决方案1】:

此处程序的当前版本有效。我测试过。 https://github.com/bhrigu123/huffman-coding/blob/master/huffman.py

#Modified code here for reference
class HeapNode:
    def __init__(self, char, freq):
        self.char = char
        self.freq = freq
        self.left = None
        self.right = None

    # defining comparators less_than and equals
    def __lt__(self, other):
        return self.freq < other.freq

    def __eq__(self, other):
        if(other == None):
            return False
        if(not isinstance(other, HeapNode)):
            return False
        return self.freq == other.freq

【讨论】:

  • 虽然链接可能很好,但请尝试引用最重要的部分,以防链接关闭或类似情况。
  • 谢谢你的建议,@Mangu
猜你喜欢
  • 2020-09-07
  • 2021-11-21
  • 1970-01-01
  • 2017-09-14
  • 2017-09-28
  • 2018-01-10
  • 2018-09-03
  • 2018-05-22
  • 2020-05-05
相关资源
最近更新 更多