python哈夫曼编码注意_[Python]哈夫曼编码

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0Fhcm9uMjMzMw==,size_16,color_FFFFFF,t_70#pic_center

生成树

from heapq import heapify, heappush, heappop

from itertools import count

"""

https://www.cnblogs.com/xuchunlin/p/7247346.html

"""

def huffman(nodes, frequent):

num = count()

trees = list(zip(frequent, num, nodes)) # num ensures valid ordering

heapify(trees) # A min-heap based on freq

while len(trees) > 1: # Until all are combined

value1, _, node1 = heappop(trees) # Get the two smallest trees

value2, _, node2 = heappop(trees)

heappush(trees, (value1 + value2, next(num), [node1, node2])) # Combine and re-add them

# print trees

return trees[0][-1]

if __name__ == ‘__main__‘:

chars = "fecbda"

weights = [5, 9, 12, 13, 16, 45]

print(huffman(chars, weights)) # [‘a‘, [[‘c‘, ‘b‘], [[‘f‘, ‘e‘], ‘d‘]]]

编码

class Node:

def __init__(self, freq):

self.left = None

self.right = None

self.father = None

self.freq = freq

def isLeft(self):

return self.father.left == self

# create Huffman-Tree创建Huffman树

def createHuffmanTree(nodes):

queue = nodes[:]

while len(queue) > 1:

queue.sort(key=lambda item: item.freq)

node_left = queue.pop(0)

node_right = queue.pop(0)

node_father = Node(node_left.freq + node_right.freq)

node_father.left = node_left

node_father.right = node_right

node_left.father = node_father

node_right.father = node_father

queue.append(node_father)

queue[0].father = None

return queue[0]

# Huffman编码

def huffmanEncoding(nodes, root):

codes = [‘‘] * len(nodes)

for i in range(len(nodes)):

node_tmp = nodes[i]

while node_tmp != root:

if node_tmp.isLeft():

codes[i] = ‘0‘ + codes[i]

else:

codes[i] = ‘1‘ + codes[i]

node_tmp = node_tmp.father

return codes

if __name__ == ‘__main__‘:

chars = [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘, ‘H‘, ‘I‘, ‘J‘, ‘K‘, ‘L‘, ‘M‘, ‘N‘]

freqs = [10, 4, 2, 5, 3, 4, 2, 6, 4, 4, 3, 7, 9, 6]

chars_freqs = zip(chars, freqs)

chars_freqs = sorted(chars_freqs, key=lambda item: item[1])

nodes = [Node(item[1]) for item in chars_freqs]

root = createHuffmanTree(nodes)

encoding_map = huffmanEncoding(nodes, root)

for item in zip(chars_freqs, encoding_map):

print(‘Character:%s freq:%-2d encoding: %s‘ % (item[0][0], item[0][1], item[1]))

复制

原文地址:https://www.cnblogs.com/sight-tech/p/13201013.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值