Python实现Huffman Code
来源:互联网 发布:mac os x安装光盘映像 编辑:程序博客网 时间:2024/06/06 01:44
class Node: def __init__(self, weight): self.weight = weight self.parent = -1 self.charCode = -1 self.tag = 0
def Huffman(consequent): """ This function creates HuffmanCode The left branch is 1 and the right branch is 0 That's meaning the small value is at left, and the big value is at right. :param consequent: Needing to encode list :return:Encoding code list """ consequentLength = len(consequent) # first step: count unique element times elementDict = dict() for se in consequent: elementDict[se] = elementDict.get(se, 0) + 1 # second step: calculate the probability of element frequency = [] for key in elementDict.keys(): frequency.append(float(elementDict.get(key)) / consequentLength) # third step: according to the frequency of every element, obtaining Huffman coding frequencyLength = len(frequency) for i in range(frequencyLength): frequency[i] = Node(frequency[i]) listLength = frequencyLength while True: minimal, maximum = findTwoMinimal(frequency) if maximum == -1: break newNode = Node(frequency[minimal].weight + frequency[maximum].weight) frequency.append(newNode) listLength += 1 frequency[minimal].parent = listLength - 1 frequency[maximum].parent = listLength - 1 frequency[minimal].charCode = 0 # the small value makes as 0 frequency[maximum].charCode = 1 # the big value makes as 1 codes = [] for i in range(frequencyLength): parent = frequency[i].parent code = str(frequency[i].charCode) while parent != -1: code = str(frequency[parent].charCode) + code parent = frequency[parent].parent codes.append(code[2:]) # Assigning an encoding for each element keys = elementDict.keys() for i in range(len(codes)): elementDict[keys[i]] = codes[i] # consequentCodes = [] codeLength = 0 for se in consequent: # consequentCodes.append(elementDict.get(se)) codeLength += len(elementDict.get(se)) # print consequentCodes return codeLength
0 0
- Python实现Huffman Code
- Huffman Tree 的构建和Huffman Code的实现
- Huffman Code
- Huffman code
- 用python实现Huffman编码
- 哈夫曼编码 (Huffman code)的实现,压缩、解压缩
- 哈夫曼编码 (Huffman code)的实现,压缩、解压缩
- huffman code and encode
- 1289 Huffman Code
- code of huffman(参考)
- Huffman Code 编码译码
- 浙大数据结构-HuffMan Code
- 基于Huffman编码的压缩软件的Python实现
- 图的学习-huffman code
- huffman编码实现
- Huffman编码的实现
- Huffman树的实现
- 实现huffman树
- java se 11
- Spring 定时任务 @Scheduled
- 前段规范(更新中)
- IDEA中集成struts2+mybatis
- 我见过最简单,方便的屏幕适配
- Python实现Huffman Code
- Python进阶(十二)-浅谈python中的方法
- JDK 源码解析 —— ThreadLocal
- express使用MongoDB数据库
- Dubbo学习笔记(二) 环境配置
- 可用性测试
- 病毒(3602017秋招真题)
- 如何将Oracle导出的数据导入MongoDB
- webots自学笔记(一)软件界面和简单模型仿真