Huffman Implementation with Python

码表

Token Frequency
a 10
e 15
i 12
s 3
t 4
space 13
n 1

生成 Huffman 编码

根据上面的码表,先生成 Huffman 树,然后生成 Huffman 编码。代码如下:

def binary_tree(val=None):
return [val, [], []] def insert_left(root, branch):
root[1] = branch def insert_right(root, branch):
root[2] = branch def get_root_val(root):
return root[0] def set_root_val(root, val):
root[0] = val def get_left_child(root):
return root[1] def get_right_child(root):
return root[2] def is_leaf(root):
if len(get_left_child(root)) == 0 and len(get_right_child(root)) == 0:
return True
return False def huffman(data):
while len(data) > 1:
data = sorted(data, key=lambda e: e[1]) root = binary_tree()
left = data.pop(0)
right = data.pop(0) insert_left(root, left[0])
insert_right(root, right[0]) data.append((root, left[1] + right[1]))
return data[0][0] def tree2code(root, code, plan):
if is_leaf(root):
plan[get_root_val(root)] = code
else:
tree2code(get_left_child(root), code+'0', plan)
tree2code(get_right_child(root), code+'1', plan) def build_data(d):
l = list()
for pair in d.items():
root = binary_tree(pair[0])
l.append((root, pair[1]))
return l if __name__ == '__main__':
d = {'a':10, 'e':15, 'i':12, 's':3, 't':4, 'space':13, 'n':1} l = build_data(d)
tree = huffman(l) plan = dict()
tree2code(tree, str(), plan)
print(plan)

运行结果得到

{'i': '00', 'space': '01', 'e': '10', 't': '1100', 'n': '11010', 's': '11011', 'a': '111'}

结果分析

根据文献[1],可以知道当前的解是最好结果。

Bibliography

[1] 《数据结构与算法分析——C语言描述》 机械工业出版社

Huffman Implementation with Python的更多相关文章

  1. Tree Implementation with Python

    Tree Implementation with Python List of List 代码如下: def binary_tree(val): return [val, [], []] def in ...

  2. [Data Structure] Stack Implementation in Python

    We can realize a Stack as an adaptation of a Python List. S.push(e)=L.append(e) S.pop()=L.pop() S.to ...

  3. naive cube implementation in python

    这篇论文中提到的naive cube算法的实现,python写出来真的就和伪代码差不多=.= 输入大约长这样,依次是 index userid country state city topic cat ...

  4. [Data Structure] Linked List Implementation in Python

    class Empty(Exception): pass class Linklist: class _Node: # Nonpublic class for storing a linked nod ...

  5. 【数据压缩】Huffman编码

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

  6. Python框架、库以及软件资源汇总

    转自:http://developer.51cto.com/art/201507/483510.htm 很多来自世界各地的程序员不求回报的写代码为别人造轮子.贡献代码.开发框架.开放源代码使得分散在世 ...

  7. Awesome Python

    Awesome Python  A curated list of awesome Python frameworks, libraries, software and resources. Insp ...

  8. Machine and Deep Learning with Python

    Machine and Deep Learning with Python Education Tutorials and courses Supervised learning superstiti ...

  9. Understanding Asynchronous IO With Python 3.4's Asyncio And Node.js

    [转自]http://sahandsaba.com/understanding-asyncio-node-js-python-3-4.html Introduction I spent this su ...

随机推荐

  1. 高危Windows系统 SMB/RDP远程命令执行漏洞 手工修复办法

     1.Windows Update更新补丁方式: 更新方法:点击“开始”->“控制面板”->“Windows Update” ,点击“检查更新”-“安装更新”: 2.检查安装结果: 点击“ ...

  2. Linux修改SSH登录端口

    Linux的默认登录端口为:22,为系统安全运维都会将端口改成其它端口. 假如我们修改的端口为:3000 1.首先要配置防火墙,允许此端口通行. /sbin/iptables -A INPUT -p ...

  3. 动手动脑(&课后实验):类和对象

    1. 以下代码为何无法通过编译?哪儿出错了? 如果类提供了一个自定义的构造方法,将导致系统不再提供默认构造方法.而此时程序中已提供了一个有一个参数的构造函数,而定义对象时却没有参数,所以程序会报错. ...

  4. php 中 get_cfg_var() 与 ini_get() 的异同

    背景 get_cfg_var() 取的值是配置文件中的值 ini_get() Gets the value of a configuration option, 则取的当前值(运行时,PHP系统定义) ...

  5. MD5、SHA1加密java 16位32位

    MD5.SHA1加密java 16位32位 import java.math.BigInteger; import java.security.MessageDigest; public class ...

  6. Unable to update the EntitySet 'T_JsAPI' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.

    前几天使用EF6的Db First模式改造了支付中心的数据访问层,废弃了ado.net. 同时,使用T4把实体类生成到了model层的PO目录下. 今天在db里新建了一张表,在edmx文件里更新模型( ...

  7. Oracle之SQL优化专题02-稳固SQL执行计划的方法

    首先构建一个简单的测试用例来实际演示: create table emp as select * from scott.emp; create table dept as select * from ...

  8. C# JArray与JObject 的使用

    STEP1.using Newtonsoft.Json.Linq; STEP2 如何获取json里的某个属性(节点)值,对其删改,新增 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 ...

  9. netframework转core时文件响应流问题

    做将framework webapi项目转成netcore平台上的webapi项目时,发现原来的返回文件响应流在netcore平台下失效.代码如下,返回pdf文件响应流,供前端显示 /// <s ...

  10. CentOS上svn checkout时报错SSL handshake failed: SSL error: Key usage violation in certificate has been det

    局域网安装了个SVN在checkout的时候报错 SSL handshake failed: SSL error: Key usage violation in certificate has bee ...