Basic-Python-Programs icon indicating copy to clipboard operation
Basic-Python-Programs copied to clipboard

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

Open vmailhot opened this issue 1 year ago • 1 comments

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

Does someone think the same thing?

vmailhot avatar Apr 09 '24 20:04 vmailhot

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)

jackson-dahl42 avatar May 13 '24 23:05 jackson-dahl42