哈夫曼编码的python实现

哈夫曼编码的实现在哈夫曼树的是线上添加了leftname和rightname的字段,以及编码字段。同样,学习哈夫曼编码的博客也是非常有趣的漫画博客:https://baijiahao.baidu.com/s?id=1664724684084187981&wfr=spider&for=pc

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x, y):
        self.val = x
        self.left = None
        self.right = None
        self.name = y

class Solution:

    def huffmantree(self, weights, forest):
        while len(weights) > 1:
            tree = TreeNode(None, None)
            tree.left = forest[0]
            tree.right = forest[1]
            tree.val = weights[0] + weights[1]
            weights.pop(0)
            weights.pop(0)
            forest.pop(0)
            forest.pop(0)
            fathernode = tree.val
            for i in range(0, len(weights)):
                if fathernode <= weights[i]:
                    weights = weights[:i] + [fathernode] + weights[i:]
                    forest = forest[:i] + [tree] + forest[i:]
                    break
                elif i == len(weights) - 1 and fathernode > weights[i]:
                    weights = weights + [fathernode]
                    forest = forest + [tree]
        return tree

    def get_huffman_code(self, tree, code, codes):
        if not tree:
            return codes
        if tree.name:
            codes[tree.name] = code
            left = code + '0'
            right = code + '1'
            self.get_huffman_code(tree.left, left, codes)
            self.get_huffman_code(tree.right, right, codes)
        else:
            left = code + '0'
            right = code + '1'
            self.get_huffman_code(tree.left, left, codes)
            self.get_huffman_code(tree.right, right, codes)
        return codes


if __name__ == '__main__':
    weights = [2, 3, 7, 9, 18, 25]
    chars = ['A', 'B', 'C', 'D', 'E', 'F']
    forest = []
    for i in range(0, len(weights)):
        forest.append(TreeNode(weights[i], chars[i]))
    S = Solution()
    tree = S.huffmantree(weights, forest)
    result = S.get_huffman_code(tree, '', {})
    for k, v in result.items():
        print(k + '=' + v)

 

你可能感兴趣的:(哈夫曼)