哈夫曼树构造
哈夫曼樹構造
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 27 18:08:26 2018@author: luogan """# 樹節點類構建 class TreeNode(object):def __init__(self, data):self.val = data[0]self.priority = data[1]self.leftChild = Noneself.rightChild = Noneself.code = "" # 創建樹節點隊列函數 def creatnodeQ(codes):q = []for code in codes:q.append(TreeNode(code))return q # 為隊列添加節點元素,并保證優先度從大到小排列 def addQ(queue, nodeNew):if len(queue) == 0:return [nodeNew]for i in range(len(queue)):if queue[i].priority >= nodeNew.priority:return queue[:i] + [nodeNew] + queue[i:]return queue + [nodeNew] # 節點隊列類定義 class nodeQeuen(object):def __init__(self, code):self.que = creatnodeQ(code)self.size = len(self.que)def addNode(self,node):self.que = addQ(self.que, node)self.size += 1def popNode(self):self.size -= 1return self.que.pop(0) # 各個字符在字符串中出現的次數,即計算優先度 def freChar(string):d ={}for c in string:if not c in d:d[c] = 1else:d[c] += 1return sorted(d.items(),key=lambda x:x[1]) # 創建哈夫曼樹 def creatHuffmanTree(nodeQ):while nodeQ.size != 1:node1 = nodeQ.popNode()node2 = nodeQ.popNode()r = TreeNode([None, node1.priority+node2.priority])r.leftChild = node1r.rightChild = node2nodeQ.addNode(r)return nodeQ.popNode()codeDic1 = {} codeDic2 = {} # 由哈夫曼樹得到哈夫曼編碼表 def HuffmanCodeDic(head, x):global codeDic, codeListif head:HuffmanCodeDic(head.leftChild, x+'0')head.code += xif head.val:codeDic2[head.code] = head.valcodeDic1[head.val] = head.codeHuffmanCodeDic(head.rightChild, x+'1') # 字符串編碼 def TransEncode(string):global codeDic1transcode = ""for c in string:transcode += codeDic1[c]return transcode # 字符串解碼 def TransDecode(StringCode):global codeDic2code = ""ans = ""for ch in StringCode:code += chif code in codeDic2:ans += codeDic2[code]code = ""return ans # 舉例 string = "AAGGDCCCDDDGFBBBFFGGDDDDGGGEFFDDCCCCDDFGAAA" t = nodeQeuen(freChar(string)) tree = creatHuffmanTree(t) HuffmanCodeDic(tree, '') print(codeDic1,codeDic2) a = TransEncode(string) print(a) aa = TransDecode(a) print(aa) print(string == aa)posted on 2018-07-27 18:14 luoganttcc 閱讀(...) 評論(...) 編輯 收藏
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: Python Elasticsearc
- 下一篇: C 语言指针理解