-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaa_2.py
46 lines (34 loc) · 1 KB
/
daa_2.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
import heapq
# python abs_path.py cmd
class Node:
def __init__(self, val, symbol) -> None:
self.val = val
self.symbol = symbol
self.huffman = ''
self.l = None
self.r = None
def __lt__(self, next):
return self.val < next.val
nodes = []
char = ['a', 'b', 'c', 'd', 'e']
freq = [100, 12, 24, 105, 38]
for i in range(len(char)):
heapq.heappush(nodes, Node(freq[i], char[i]))
while len(nodes) > 1:
left = heapq.heappop(nodes)
right = heapq.heappop(nodes)
left.huffman = '0'
right.huffman = '1'
newNode = Node(left.val + right.val, left.symbol + right.symbol)
newNode.l = left
newNode.r = right
heapq.heappush(nodes, newNode)
def printNodes(node, val=''):
newVal = val + node.huffman
if node.l:
printNodes(node.l, newVal)
if node.r:
printNodes(node.r, newVal)
if not node.l and not node.r:
print(f"{node.symbol} -> {newVal}")
printNodes(nodes[0])