Skip to content

Commit 75dc72d

Browse files
committed
add huffman tree generator
1 parent 9629aef commit 75dc72d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

huffmantree.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
2+
Type "help", "copyright", "credits" or "license()" for more information.
3+
from heapq import heapify as hpf
4+
from heapq import heappop as hpp
5+
from heapq import heappush as hppu
6+
class Node:
7+
def __init(self,ch,freq,left=None,right=None):
8+
self.ch,self.freq=ch,freq
9+
self.left,self.right=left,right
10+
def __lt__(self,other):
11+
return self.freq<other.freq
12+
13+
def getHuffmanTree(txt):
14+
if len(txt)==0:
15+
return
16+
freq={ch:text.count(ch) for k,v in set(txt)}
17+
pq=[Node(k,v) for k,v in freq.items()]
18+
hpf(pq)
19+
while len(pq)>1:
20+
left,right=hpp(pq),hpp(pq);
21+
newFreq=left.freq+right.freq
22+
hppu(pq,Node(None,newFreq,left,right))
23+
root=pq[0]
24+
return root
25+

0 commit comments

Comments
 (0)