from operator import attrgetter import math class Leaf: def __init__(self, value, prob): self.value=value self.prob=prob def __str__(self): return "("+str(self.value)+","+str(self.prob)+")" def getEncoding(self,accumulated): return [[accumulated,self.value]] class Node: def __init__(self,left,right): self.left=left self.right=right self.prob=left.prob+right.prob def __str__(self): return "[Left: "+self.left.__str__()+" Right: "+self.right.__str__()+"]" def getEncoding(self, accumulated): return self.left.getEncoding(accumulated+"0")+self.right.getEncoding(accumulated+"1") class HDictionary: def __init__(self, encoding): self.encoding = encoding self.chars = [] self.bitstrings = [] for a in self.encoding: self.bitstrings.append(a[0]) self.chars.append(a[1]) def getBits(self,c): return self.bitstrings[self.chars.index(c)] strIn = """ """ nodes = [] chars=[] freq=[] for c in strIn: if c in chars: freq[chars.index(c)]+=1 else: chars.append(c) freq.append(1) for i in range(0,len(chars)): nodes.append(Leaf(chars[i],freq[i])) while(len(nodes)>1): nodes.sort(key=attrgetter('prob'),reverse=True) nodes.append(Node(nodes.pop(),nodes.pop())) print nodes[0] enc = nodes[0].getEncoding("") print enc hd = HDictionary(enc) bits = "" for c in strIn: bits+=hd.getBits(c) print bits print str(int(math.ceil(len(bits)/8.0)))+" vs "+str(len(strIn))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question