-
Notifications
You must be signed in to change notification settings - Fork 0
/
huffman.py
86 lines (71 loc) · 1.79 KB
/
huffman.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# coding=utf-8
from heapq import heapify, heappush, heappop
from itertools import count
from Tree import *
from dice import *
def calcWeight(ll):
'''
This func set to calculate the weight of each code
:param ll: ll is the source of
:return:
'''
weightRes = []
# two lines below is to get all the unique code from source
tmplist = list(set(ll))
length = float(len(ll))
for i in tmplist:
num, count = i, ll.count(i)
lweight = count / length
weightRes.append(lweight)
return tmplist, weightRes
def createHuffTree(seq, frq):
num = count()
trees = list(zip(frq, num, seq))
heapify(trees)
while len(trees) > 1:
# two lines below aim to find the most min node of tree
fa, _, a = heappop(trees)
fb, _, b = heappop(trees)
n = next(num)
heappush(trees, (fa + fb, n, [a, b]))
# print trees
return trees[0][-1]
def avelength(dict,freq,seq):
"""
to calculate the averaage length of huffman code
:param dict:
:return:
"""
length=0.0
for i in range(len(seq)):
length+=len(dict[seq[i]])*freq[i]
return length
def HuffEncode(srcLst, huffDict):
"""
:param srcStr:
:param huffDict:
:return:
"""
dest = ''
for i in srcLst:
dest += huffDict[i]
return dest
def HuffDecode(srcStr, huffDict):
# Reverse the key and value of HuffDict.Let value be key and key be value
decodeDict = {value: key for key, value in huffDict.items()}
tmpStr = ''
result = []
for i in srcStr:
tmpStr += i
if tmpStr in decodeDict.keys():
result.append(decodeDict[tmpStr])
tmpStr = ''
else:
pass
return result
def test():
'''
test func
:return: none
'''
test()