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

时间:2017-12-20 18:14:07

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

当我尝试将节点推送到堆上以获取霍夫曼树时,我收到此错误:

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

1 个答案:

答案 0 :(得分:4)

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