一、问题

利用二叉树的结构对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. 无线安全审计工具FruityWifi初体验

    FruityWIfi是一款有名的无线安全审计的开源工具,其灵感来自于wifipineapple,目前该工具已经更新到2.4.它能够让用户通过web界面来控制和管理模块,十分方便.FriutyWifi最 ...

  2. Odoo field字段标签属性详解

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/10826356.html 标签属性 1) name:标识字段名称 2)string:标签文本,如果我们想要覆盖 ...

  3. <code> 标签 让一段计算机代码显示在网页中

    <code> 标签 解释:要让一段计算机代码显示在网页中,那么这段代码需要用<code> 标签包起来,不然他会被当作网页的代码被 运行. 例如: <code>< ...

  4. scrapy 改 scrapy-redis

    1.spider 修改 class CgysSpider(scrapy.Spider): name = 'clispider' start_urls = ['https://search.bilibi ...

  5. python基础语法19 面向对象总结,pickle保存对象注意事项

    面向对象的三大特性: 继承,封装,多态 多态的三种表现形式:鸭子类型,继承父类,继承抽象类 pickle保存对象注意事项 class Foo: y = 20 def __new__(cls, *arg ...

  6. 网站调试时记得关闭火狐adblock插件

    由于特殊需要,xmyanke需要在网站右侧添加一个弹窗,第一个网站加上代码后可以正常显示,第二个网站却怎么也看不到图片,同样的安装方法为什么差别那么大呢?重新复制代码还是不行,再试一遍,依然如此,wi ...

  7. VIJOS-P1320 清点人数

    JDOJ 1427: VIJOS-P1320 清点人数 题目传送门 Description 初始时,火车上没有学生:当同学们开始上火车时,年级主任从第一节车厢出发走到最后一节车厢,每节车厢随时都有可能 ...

  8. html-前端内容初识

    HTML解释: HTML是英文Hyper Text Mark-up Language(超文本标记语言)的缩写,他是一种制作万维网页面标准语言(标记).相当于定义统一的规则(W3C),大家都来遵守他,这 ...

  9. 【java】定时任务@Scheduled

    每隔5秒执行一次:"*/5 * * * * ?" 每隔1分钟执行一次:"0 */1 * * * ?" 每天23点执行一次:"0 0 23 * * ?& ...

  10. org.apache.hadoop.util.Shell demo/例子

    package cn.shell; import java.io.IOException; import org.apache.hadoop.util.Shell; public class Shel ...