资源简介
使用python编写的一套代码,可以实现随机文本生成,字符串字符统计还有哈夫曼编码。可以转换哈夫曼编码到010101,然后解码生成字符串
代码片段和文件信息
#Huffman Encoding
#Tree-Node Type
import random
class Node:
def __init__(selffreq):
self.left = None
self.right = None
self.father = None
self.freq = freq
def isLeft(self):
return self.father.left == self
#create nodes创建叶子节点
def createNodes(freqs):
return [Node(freq) for freq in freqs]
#create Huffman-Tree创建Huffman树
def createHuffmanTree(nodes):
queue = nodes[:]
print(queue) #一个个node的地址
#每次对queue进行排序,
while len(queue) > 1:
queue.sort(key=lambda item:item.freq) #reverse = false
node_left = queue.pop(0)
node_right = queue.pop(0)
node_father = Node(node_left.freq + node_right.freq)
node_father.left = node_left
node_father.right = node_right
评论
共有 条评论