我决定实现一个小的 Huffman 编码脚本。在一个小的概率列表上对其进行测试后,我在构建过程中打印树时得到正确的结果,如果不打印,则得到错误的结果。问题的原因可能是什么?
这是我的代码:
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