2

我决定实现一个小的 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
4

1 回答 1

2

这真的与印刷无关。你的问题在这里:

heapq.heappush(probs,f)

f是您的InternalNode类的一个实例,但该类没有定义任何顺序。因此 Python 默认按内存地址InternalNode对实例进行排序。这根本不是您想要的,内存地址因您所做的其他事情而异(打印、运行 PDB、创建或删除其他对象......)。

__cmp__最简单的解决方法是向您的类添加一个方法:

    def __cmp__(a, b):
        return cmp(a.prob, b.prob)

然后输出将是一致的。

编辑:嗯,你也得到了LeafNode实例的内存地址排序,所以__cmp__也添加一个。

于 2013-11-10T22:10:36.207 回答