一、问题

利用二叉树的结构对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. 开机注册联通2G网络

    2/3G PLMN LIST 在MM_RATCM_PLMN_LIST_CNF或NWSEL_MM_PLMN_SEARCH_CNF消息中可以查看2,3G搜到的PLMN LIST 内容如下: RAT:Rad ...

  2. 0x02 Python logging模块利用配置加载logger

    目录 logging模块利用配置加载logger 方式一模板:logging.config.dictConfig(config_dict) logging模块利用配置加载logger logging. ...

  3. MySQL数据物理备份之xtrabackup

    percona-xtrabackup 它是开源免费的支持MySQL 数据库热备份的软件,它能对InnoDB和XtraDB存储引擎的数据库非阻塞地备份.它不暂停服务创建Innodb热备份: 为mysql ...

  4. PS下修改背景色

    1.打开要修改的图片 2.选择左侧的快速选择工具,右键选择魔法棒 3.在图片上点击左键选取背景 4.菜单栏选择编辑,点击填充 5.在填充选项框中选择“颜色",点击选取要使用的颜色,确定

  5. Chrome无界面启动使用

    Method1: from selenium import webdriver # 创建chrome参数对象opt = webdriver.ChromeOptions() # 把chrome设置成无界 ...

  6. 【JavaScript】案例一:使用JS完成注册页面表单校验——事件(onsubmit&onfocus&onblur)

    (一)初版:事件(onsubmit) 步骤分析: 第一步:确定事件(onsubmit)并为其绑定一个函数 第二步:书写这个函数(获取用户输入的数据<获取数据时需要在指定位置定义一个 id> ...

  7. BSGS算法(大小步算法)

    $BSGS$ 算法 $Baby\ Steps\ Giant\ Steps$. 致力于解决给定两个互质的数 $a,\ p$ 求一个最小的非负整数 $x$ 使得 $a^x\equiv b(mod\ p)$ ...

  8. 第03节-BLE协议各层数据格式概述

    本篇博客根据韦大仙的视频,整理所得. 对于BLE系统,它分为上下两块.上面那一块,我们称为host主机.下面这一块是controller,你可以简单的认为它就是一个蓝牙芯片. 对于host这一块,它运 ...

  9. woocommerce隐藏breadcrumb面包屑导航

    woocommerce已经集成比较完善的组件,当然也包含breadcrumb面包屑导航,但是我们如果调整一下breadcrumb的位置要如何操作呢?首先要先把woocommerce隐藏breadcru ...

  10. JDOJ 2197: 校门外的树

    JDOJ 2197: 校门外的树 题目传送门 Description 某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是1米. 我们可以把马路看成一个数轴,马路的一端在数轴1的位置,另一 ...