用python实现哈夫曼树和哈夫曼编码
昨晚亢神现场演示了一下构造哈夫曼树与进行哈夫曼编码,于是回来之后自己也简单写了一个
哈夫曼树的基本概念
代码
直接上代码
iput=[('zrd',5),('sea',3),('handsome',2),('beauty',1),('rd',1),('love',2)]
#初始化
n=len(iput)
father=[-1]*2*n
pot=[0]*2*n
origin=[(i,v) for i,v in zip(range(n),dict(iput).keys())]
souce=[(i,v) for i,v in zip(range(n),dict(iput).values())]
#创建哈夫曼树
while(len(souce)>1):
souce.sort(key=lambda k:k[1])
x=souce.pop(0)
y=souce.pop(0)
father[y[0]]=father[x[0]]=n
pot[x[0]]=0;pot[y[0]]=1
souce.append((n,x[1]+y[1]))
n=n+1
father.pop()
pot.pop()
#由哈夫曼树生成哈夫曼编码
dic={}
for i,name in origin:
st=''
t=i
while father[t]!=-1:
st=str(pot[t])+st
t=father[t]
dic[name]=st
print(dic)
输出结果为
{'zrd': '11', 'sea': '01', 'handsome': '100', 'beauty': '000', 'rd': '001', 'love': '101'}
创造出的哈夫曼树为

本文通过Python代码展示了如何构建哈夫曼树并生成哈夫曼编码。使用具体示例说明了编码过程,适用于数据压缩场景。

8465

被折叠的 条评论
为什么被折叠?



