【python】霍夫曼树

【python】霍夫曼树_第1张图片

# 节点类
class Node:
    def __init__(self, name=None, value=None):
        self._name = name
        self._value = value
        self._left = None
        self._right = None

# 霍夫曼树类
class HuffmanTree:

    # 根据Huffman树的思想:以叶子节点为基础,根据value排序,反向创建Huffman树
    def __init__(self, char_weights):
        self.a = [Node(key, value) for key, value in dict.items()]
        while len(self.a) != 1:
            self.a.sort(key=lambda node: node._value, reverse=True)
            c = Node(value=(self.a[-1]._value + self.a[-2]._value))
            c._left = self.a.pop(-1)
            c._right = self.a.pop(-1)
            self.a.append(c)
        self.root = self.a[0]
        self.b = list(range(20))

    # 递归的思想生成编码
    def pre(self, tree, length):
        node = tree
        if (not node):
            return

        elif node._name :
            str_num = ""
            for i in range(length):
                str_num += str(self.b[i]) + " "
            print(node._name + '编码为:',str_num)
            return

        self.b[length] = 0
        self.pre(node._left, length+1)

        self.b[length] = 1
        self.pre(node._right, length+1)

    # 生成霍夫曼编码
    def get_code(self):
        self.pre(self.root, 0)


if __name__ == '__main__':

    dict = {"a": 9, "b": 12, "c": 6, "d": 3,"e":5, "f": 15}
    tree = HuffmanTree(dict)
    tree.get_code()

 

输出结果

a编码为: 0 0 
b编码为: 0 1 
c编码为: 1 0 0 
d编码为: 1 0 1 0 
e编码为: 1 0 1 1 
f编码为: 1 1

 

你可能感兴趣的:(python)