Python 类型错误:'<';在';HeapNode';和';HeapNode';
当我尝试将一个节点推送到huffman树的堆上时,我得到以下错误:Python 类型错误:'<';在';HeapNode';和';HeapNode';,python,python-3.x,heap,nodes,huffman-code,Python,Python 3.x,Heap,Nodes,Huffman Code,当我尝试将一个节点推送到huffman树的堆上时,我得到以下错误: TypeError:“此处程序的当前版本有效。我做了测试 #此处修改代码以供参考 类HeapNode: 定义初始化(self、char、freq): self.char=char self.freq=freq self.left=无 self.right=无 #定义比较器小于等于 定义(自身、其他): 返回self.freq
TypeError:“此处程序的当前版本有效。我做了测试
#此处修改代码以供参考
类HeapNode:
定义初始化(self、char、freq):
self.char=char
self.freq=freq
self.left=无
self.right=无
#定义比较器小于等于
定义(自身、其他):
返回self.freq
它看起来像是HeapNode
不支持排序(它没有\uuu lt\uuuu
或\uuu eq\uuuu
等方法),我相信@mgilson是正确的。您需要重载比较运算符。还有,好名字。你试着打电话给接线员,虽然链接可能很好,但试着引用最重要的部分,以防链接中断或类似情况。谢谢你的建议,@Mangu
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)
#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