You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
huffmantree.py has many error, so it's useless #482
def getHuffmanTree(txt):
if len(txt) == 0:
return
freq = {ch: txt.count(ch) for ch in set(txt)}
pq = [Node(k, v) for k, v in freq.items()]
hpf(pq)
while len(pq) > 1:
left, right = hpp(pq), hpp(pq)
newFreq = left.freq + right.freq
hppu(pq, Node(None, newFreq, left, right))
root = pq[0]
return root
def printTree(node, level=0, prefix=''):
if node is not None:
print(' ' * level + prefix + str(node.freq))
if node.left is not None or node.right is not None:
printTree(node.left, level + 1)
printTree(node.right, level + 1)
Activity
jackson-dahl42 commentedon May 13, 2024
Hello vmailhot, I tried fixing the code in the file.
from heapq import heapify as hpf
from heapq import heappop as hpp
from heapq import heappush as hppu
class Node:
def init(self, ch, freq, left=None, right=None):
self.ch, self.freq = ch, freq
self.left, self.right = left, right
def lt(self, other):
return self.freq < other.freq
def getHuffmanTree(txt):
if len(txt) == 0:
return
freq = {ch: txt.count(ch) for ch in set(txt)}
pq = [Node(k, v) for k, v in freq.items()]
hpf(pq)
while len(pq) > 1:
left, right = hpp(pq), hpp(pq)
newFreq = left.freq + right.freq
hppu(pq, Node(None, newFreq, left, right))
root = pq[0]
return root
def printTree(node, level=0, prefix=''):
if node is not None:
print(' ' * level + prefix + str(node.freq))
if node.left is not None or node.right is not None:
printTree(node.left, level + 1)
printTree(node.right, level + 1)
root = getHuffmanTree("hello world")
printTree(root)