哈夫曼树与哈夫曼编码的实现——python

哈夫曼树与哈夫曼编码的实现——python

#创建节点类,用于每个节点的生成
class hfmNOde():
    def __init__(self):
        self.name = None
        self.weight = None
        self.leftchild = None
        self.rightchild = None
        self.parent = None
#构建哈夫曼树
def CreatTree(data):
    #将传入的数据字典,key和value对换,便于后面使用
    new_dict = {v : k for k, v in data.items()}
    #生成权重列表,用于后面生成哈夫曼树
    weight=[i for  i in new_dict ]
    #生成节点字典,用于储存各个节点,key为每个节点权重,value为对应节点
    #节点属性填入name属性和weight属性
    node_dict={}
    for i in new_dict:
        node=hfmNOde()
        node.name=new_dict[i]
        node.weight=i
        node_dict[i]=node
    
    #构建哈夫曼树,直到只剩一个根节点结束构建
    #每两个权重最小节点生成一个父节点
    while len(weight) != 1:
        #找到最小两个权重节点,在权重列表中去除
        min1=min(weight)
        weight.remove(min1)
        min2=min(weight)
        weight.remove(min2)
        #生成父节点
        #父节点左孩子为最小权重节点,右孩子为倒数第二权重节点
        #父节点权重为两个孩子权重和
        parentNode=hfmNOde()
        parentNode.leftchild=node_dict[min1]
        parentNode.rightchild=node_dict[min2]
        parentNode.weight=min1+min2
        #将两个孩子的parent属性都设为该父节点
        node_dict[min1].parent=parentNode
        node_dict[min2].parent=parentNode
        #将父节点权重加入权重列表,并在节点字典中生成对应数据(key为权重,value为节点)
        weight.append(parentNode.weight)
        node_dict[parentNode.weight]=parentNode
    return parentNode

#哈夫曼树解码
#利用递归进行解码
def hfmcode(tree,code="",dict={}):
    #若左孩子存在,code加1,若退出该左孩子,则将code最后一个减去
    if tree.leftchild:
        code=code+"1"
        dict=hfmcode(tree.leftchild,code,dict)  
        code=code[0:-1]
    #与上述相同
    if tree.rightchild:
        code=code+"0"
        dict=hfmcode(tree.rightchild,code,dict)   
        code=code[0:-1]
    #若左右孩子不存在,说明到达根节点
    #储存当前节点的属性及编码
    if tree.leftchild == None and tree.rightchild == None:
        dict[tree.name]=code
    return dict

data={"a":45,"b":13,"c":12,"d":16,"e":9,"f":5}
tree=CreatTree(data)
print(hfmcode(tree))


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值