一、问题

利用二叉树的结构对Huffman树进行编码,实现最短编码

二、解决

 # 构建节点类
class TreeNode:
def __init__(self, data):
"""
:data is a tuple the first element is value and the second is priority
:param data:
"""
self.value = data[0]
self.priority = data[1]
self.left_child = None
self.right_child = None
self.code = "" # 创建树节点队列的函数
def create_node_queue(codes):
queue = []
for code in codes:
queue.append(TreeNode(code))
return queue # 在队列中间添加新的节点元素并保证优先度从大到小排列
def add_queue(queue, node_new):
if len(queue) == 0:
return [node_new]
for i in range(len(queue)):
if queue[i].priority >= node_new.priority:
return queue[:i] + [node_new] + queue[i:]
return queue + [node_new] # 节点队列类
class NodeQueue:
def __init__(self, code):
self.queue = create_node_queue(code)
self.size = len(self.queue) def add_node(self, node):
self.queue = add_queue(self.queue, node)
self.size += 1 def pop_node(self):
self.size -= 1
return self.queue.pop(0) # 各个字符在字符串中出现的次数 即计算优先度
def frequent_char(string_s):
store_d = {}
for c in string_s:
if c not in store_d:
store_d[c] = 1
else:
store_d[c] += 1
return sorted(store_d.items(), key=lambda x: x[1]) # 创建Huffman树
def create_huffman_tree(node_queue):
while node_queue.size != 1:
node1 = node_queue.pop_node()
node2 = node_queue.pop_node()
r_1 = TreeNode([None, node1.priority + node2.priority])
r_1.left_child = node1
r_1.right_child = node2
node_queue.add_node(r_1)
return node_queue.pop_node() code_dict1 = {}
code_dict2 = {} # 由Huffman树得到的Huffman编码表
def huffman_code_dict(head, x):
# global code_dict, code_list
if head:
huffman_code_dict(head.left_child, x + "")
head.code += x
if head.value:
code_dict2[head.code] = head.value
code_dict1[head.value] = head.code
huffman_code_dict(head.right_child, x + "") # 字符串编码
def trans_encode(string_s):
# global code_dict1
trans_code = ""
for c in string_s:
trans_code += code_dict1[c]
return trans_code # 字符串解码
def trans_decode(string_s):
# global code_dict1
code = ""
answer = ""
for c in string_s:
code += c
if code in code_dict2:
answer += code_dict2[code]
code = ""
return answer

三、总结
利用Huffman树的编码形式可以进行数据的压缩,因此Huffman的应用也很广泛。在此记录一下方便以后查看。

python实现Huffman编码的更多相关文章

  1. 【数据压缩】Huffman编码

    1. 压缩编码概述 数据压缩在日常生活极为常见,平常所用到jpg.mp3均采用数据压缩(采用Huffman编码)以减少占用空间.编码\(C\)是指从字符空间\(A\)到码字表\(X\)的映射.数据压缩 ...

  2. [老文章搬家] 关于 Huffman 编码

    按:去年接手一个项目,涉及到一个一个叫做Mxpeg的非主流视频编码格式,编解码器是厂商以源代码形式提供的,但是可能代码写的不算健壮,以至于我们tcp直连设备很正常,但是经过一个UDP数据分发服务器之后 ...

  3. python基础之编码问题

    python基础之编码问题 本节内容 字符串编码问题由来 字符串编码解决方案 1.字符串编码问题由来 由于字符串编码是从ascii--->unicode--->utf-8(utf-16和u ...

  4. Python基础-字符编码与转码

    ***了解计算机的底层原理*** Python全栈开发之Python基础-字符编码与转码 需知: 1.在python2默认编码是ASCII, python3里默认是utf-8 2.unicode 分为 ...

  5. Huffman编码

    #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdio> #include <cstri ...

  6. python中的编码问题:以ascii和unicode为主线

      1.unicode.gbk.gb2312.utf-8的关系 http://www.pythonclub.org/python-basic/encode-detail 这篇文章写的比较好,utf-8 ...

  7. 优先队列求解Huffman编码 c++

    优先队列小析      优先队列的模板: template <class T, class Container = vector<T>,class Compare = less< ...

  8. python与字符集编码

    讲的比较明白的博客:http://www.cnblogs.com/huxi/archive/2010/12/05/1897271.html 以上面博文的汉为例子,汉字的GBK编码是baba, UNIC ...

  9. 第三篇:python基础之编码问题

    python基础之编码问题   python基础之编码问题 本节内容 字符串编码问题由来 字符串编码解决方案 1.字符串编码问题由来 由于字符串编码是从ascii--->unicode---&g ...

随机推荐

  1. Vue组件间通信6种方式

    摘要: 总有一款合适的通信方式. 作者:浪里行舟 Fundebug经授权转载,版权归原作者所有. 前言 组件是 vue.js 最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的 ...

  2. Shell 编程 数组

    本篇主要写一些shell脚本数组的使用. 数组定义 数组名=(value0 value1 vlaue2 ...) 数组名=([0]=value [1]=value [2]=vlaue ...) 列表名 ...

  3. passwd修改密码失败,报鉴定令牌操作错误

    出现这个情况,从四个方面来分析: 1./usr/bin/passwd 的权限中没有添加s即SUID特殊权限 即:-rwxr-xr-x. 1 root root 27000 8月  22 2010 /u ...

  4. 性能测试基础---jmeter参数化、关联、事物、检查的等

    ·Jmeter脚本增强·性能测试的脚本增强技术:参数化.关联.事务.检查点.思考时间和集合点. ·参数化:在Jmeter中,实现参数化的方式很多.本质上来说,参数化的实现方式有两种:·文件方式:一般建 ...

  5. 谷歌学术出现We're sorry解决办法

    出现这个的原因应该是同ip段的或者就是这个ip曾经是个google的黑名单ip,因为恶意爬取谷歌学术了.解决办法就是申请Hurricane Electric Free IPv6 Tunnel Brok ...

  6. 爬虫-selenium的使用

    安装 pip install selenium 开始 # coding=utf-8 from selenium import webdriver # 引用selenium库 import time # ...

  7. MAC上配置idea环境时排查问题

    现象:没有使用走公司maven仓库的setting.xml文件时,只有公司内部依赖 没有找到在idea的maven配置中指定 公司setting.xml后,所有的文件都提示找不到 解决办法:把公司se ...

  8. 将HashMap转换为List

    背景 ​ SpringBoot中,使用@RquestBody注解 hashMap 接收多个参数的json字符串数据,包括一个数组和一个int值.数组中为一个个的对象组成. 问题 ​ 使用 map.ge ...

  9. CPU中断的工作原理,从最底层讲起

    前言 中断的概念属于硬件层.虽然我们在进行软件编程时不会直接使用中断,但理解它对我们来说依然重要. 我们在使用线程切换及状态管理.异常处理.硬件与处理器的交互.I/O操作等指令时,中断都在默默的为我们 ...

  10. linux网络编程之用socket实现简单客户端和服务端的通信(基于UDP)

    单客户端和服务端的通信(基于UDP)   代码 服务端代码socket3.c #include<sys/types.h> #include<sys/socket.h> #inc ...