【发布时间】: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)
【问题讨论】:
-
看起来
HeapNode不支持排序(它没有__lt__或__eq__等方法) -
我相信@mgilson 是正确的。您需要重载比较运算符。还有,好听的名字。
-
您尝试在两个堆节点上调用 operator
<,但您从未定义过这样的方法。
标签: python python-3.x heap nodes huffman-code