python - 类型错误 : '<' not supported between instances of 'HeapNode' and 'HeapNode'

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

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

类型错误:“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

最佳答案

此处程序的当前版本有效。我测试过。 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

关于python - 类型错误 : '<' not supported between instances of 'HeapNode' and 'HeapNode' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47912064/

相关文章:

python - 我可以将单词或句子与 Python 中预先向量化的句子语料库进行匹配以进行 NL 处理吗?

python - 如何在cython中编译pyqt5和python代码

python - 使用堆的中值维护

algorithm - Prim算法的运行时间

python - 从 httplib.HTTP(s)Connection 继承时处理 SSL 和非 SSL 连接

python - 引发连接错误(连接中止,BadStatusLine): using python and Last. fm API

python - 如何计算条件列中值的频率?

python 2.7和3.3子进程模块区别

Python日志模块: how to save log to a file if (and only if) assertion test fails?

algorithm - 将二叉堆的大小限制为前 N 个元素