一、问题

利用二叉树的结构对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. iOS 原生推送(APNS)的实现

    1.前期准备工作 创建你的APNs keys 或者 创建推送证书,这两个创建一个即可实现推送.这两个创建一个即可实现推送.这两个创建一个即可实现推送.重要的事情说三遍,我看评论区有小伙伴误解. 1.  ...

  2. 普通Java项目中使用Sl4j+Log4j2打印日志

        因工作需要,采用JavaFx开发了一个windows窗口程序.在开发过程中,由于没有引入日志框架,只能自己手动在控制台打印些信息,给调试带来了很多麻烦:因此决定引入日志框架.由于之前接触的项目 ...

  3. 十八、Python面向对象之魔术方法

    1.类的比较 class A(object): def __init__(self,value): self.value = value def __eq__(self,other): return ...

  4. A站(ACFun)爬虫爬取并播放、下载视频(JAVA)

    本文使用的工具有vlc+ffmpeg+phantomjs 一般视频网站的视频地址暴露的方式有两种: 1.html直接暴露 2.通过ajax异步返回. A站使用的方式是第二种.针对第一种方式,直接使用j ...

  5. Unity 渲染教程(一):矩阵

    转载:http://gad.qq.com/program/translateview/7181958 创建立方体网格.· 支持缩放.位移和旋转. · 使用变换矩阵. · 创建简单的相机投影. 这是关于 ...

  6. 浅析 fstab 与移动硬盘挂载方法

    本文转自 Steins;Lab,非常详细地介绍了树莓派上 fstab 的配置项. 近期自己的Raspberry Pi出了点问题,总结总结便有了这篇文章. 本文首先记录“移动硬盘挂载”实际发生的问题,然 ...

  7. Kibana 的 docker 镜像使用

    1.dockhub镜像网址:https://hub.docker.com/_/kibana 2.下载镜像: docker pull kibana:7.4.0 3.创建容器(Kibana 默认的端口为5 ...

  8. java任务调度之Timer定时器

    定时器相信大家都不陌生,平时使用定时器就像使用闹钟一样,我们可以在固定的时间做某件事,也可以在固定的时间段重复做某件事,今天就来分析一下java中自带的定时任务器Timer. 一.Timer基本使用 ...

  9. mybatis框架-choose when otherwise 的使用

    需求:模拟实际业务情况,传入多条件进行查询 /** * 需求:模拟实际业务,用户传入多个条件,进行用户列表信息的查询 * @param roleids * @return */ public List ...

  10. 【java异常】Unable to install breakpoint in

    这个是断点失效,把那个断点双击清理掉就完了. 具体原因,以后再写.