Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

huffmantree.py has many error, so it's useless #482

Open
vmailhot opened this issue Apr 9, 2024 · 1 comment
Open

huffmantree.py has many error, so it's useless #482

vmailhot opened this issue Apr 9, 2024 · 1 comment

Comments

@vmailhot
Copy link

vmailhot commented Apr 9, 2024

huffmantree.py has many syntax and logical error, I suggest to remove the file.

Does someone think the same thing?

@jackson-dahl42
Copy link

jackson-dahl42 commented 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants