我决定实现一个小的霍夫曼编码脚本。在一个小的概率列表上测试之后,我在构建期间打印树时获得了正确的结果,如果不这样做,则会得到错误的结果。可能是问题的原因是什么?
这是我的代码:
from __future__ import division
import heapq
class LeafNode:
def __init__(self,symbol,prob):
self.symbol = symbol
self.prob = prob
def __repr__(self):
return "(%s: %s)" % (self.symbol, self.prob)
class InternalNode:
def __init__(self,prob,left,right):
self.prob = prob
self.left = left
self.right= right
def __repr__(self):
return "(internal : %s)" % (self.prob)
def getDict(seq):
d = dict()
for symbol in seq:
if symbol in d:
d[symbol] += 1
else:
d[symbol] = 1
return d
def returnProbList(seq):
data = getDict(seq)
sum_of_all = sum(data.values())
l = sorted(data.items(), key=lambda x:x[1])
return [LeafNode(x[0], x[1]/sum_of_all) for x in l]
def createTree(probs):
heapq.heapify(probs)
while len(probs) > 1:
a = heapq.heappop(probs)
b = heapq.heappop(probs)
print a,b #removing this shows wrong results.
f = InternalNode(a.prob+b.prob,a,b)
heapq.heappush(probs,f)
return probs[0]
def printSymbols(tree, seq = ''):
if isinstance(tree, InternalNode):
printSymbols(tree.left, seq+'0')
printSymbols(tree.right, seq+'1')
else:
print tree.symbol, seq
s = "This is some short text I have written. It seems that space is the most common symbol."
#l = returnProbList(s)
l = []
l.append(LeafNode('a4',0.05))
l.append(LeafNode('a3',0.2))
l.append(LeafNode('a2',0.35))
l.append(LeafNode('a1',0.4))
#print l
tree = createTree(l)
printSymbols(tree)
使用pdb对其进行处理甚至给出了不同的结果。
#Without print
a4 00
a3 01
a2 10
a1 11
#With print
a1 0
a4 100
a3 101
a2 11
#With pdb
a1 0
a2 10
a3 110
a4 111
答案 0 :(得分:2)
这与打印无关。你的问题在这里:
heapq.heappush(probs,f)
f
是您的InternalNode
类的实例,但该类未定义任何排序。因此,Python默认按内存地址对InternalNode
实例进行排序。这根本不是你想要的,内存地址取决于你做了什么(打印,运行PDB,创建或删除其他对象......)。
最简单的解决方法是向您的班级添加__cmp__
方法:
def __cmp__(a, b):
return cmp(a.prob, b.prob)
然后输出将保持一致。
编辑:嗯,您还获得了LeafNode
个实例的内存地址排序,因此也要添加__cmp__
。