小黑算法成长日记15:哈夫曼编码

import math
def createHuffmanTree(arr,code):
    n = len(arr)    # 字符的数量
    Nodes = [{'char':item['char'],'value':item['value'],'lchild':-1,'rchild':-1,'parent':-1} for item in arr]    # 节点数组
    [Nodes.append({'char':'*','value':'*','lchild':-1,'rchild':-1,'parent':-1}) for i in range(n-1)]    # n-1个非叶子节点插入数组
    for i in range(n - 1):    # 分别初始化n-1个非叶子节点
        parent = i + n    # 此次循环所操作的非叶子节点索引
        t1 = -1    # 第一最小值的索引
        Min1 = math.inf     # 第一最小值的大小
        for k in range(parent):    
            if Nodes[k]['parent'] == -1:    # 只对没有parent的节点进行考虑
                if Nodes[k]['value'] < Min1:
                    Min1 = Nodes[k]['value']
                    t1 = k
        Min2 = math.inf    # 第二最小值
        t2 = -1    # 第二最小值的索引
        for k in range(parent):    
            if Nodes[k]['parent'] == -1 and k != t1:    # 将第一最小值不予考虑
                if Nodes[k]['value'] < Min2:
                    Min2 = Nodes[k]['value']
                    t2 = k
        # 将子节点与父节点进行链接
        Nodes[parent]['lchild'] = t1
        Nodes[parent]['rchild'] = t2
        Nodes[parent]['value'] = Min1 + Min2
        Nodes[t1]['parent'] = parent
        Nodes[t2]['parent'] = parent
    decodes = {}
    print('1.编码结果:')
    for i in range(n):
        result = []
        parent = Nodes[i]['parent']
        c = i
        while parent != -1:    # 依次从底向上遍历,直到根节点位置
            if Nodes[parent]['lchild'] == c:
                result.append('0')
            else:
                result.append('1')
            c = parent
            parent = Nodes[parent]['parent']
        result = result[::-1]    # 逆转数组为最终编码
        result = ''.join(result)
        print(Nodes[i]['char'],'----->',result)
        decodes[result] = Nodes[i]['char']
    print('2.解码结果:')    # 将code进行解码
    temp = []
    s = []
    for i in code:
        temp.append(i)
        decode = ''.join(temp)
        if decode in decodes.keys():
            s.append(decodes[decode])
            temp = []
    print(s)
arr = [{'char':'a','value':30},{'char':'b','value':5},{'char':'c','value':10},{'char':'d','value':20}]
createHuffmanTree(arr,'01000101101110')

运行结果:
1.编码结果:
a -----> 0
b -----> 100
c -----> 101
d -----> 11
2.解码结果:
[‘a’, ‘b’, ‘a’, ‘c’, ‘c’, ‘d’, ‘a’]

你可能感兴趣的:(小黑算法成长日记15:哈夫曼编码)