Skip to content

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

Open

Description

@vincent-mailhot

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

Does someone think the same thing?

Activity

  1. jackson-dahl42 commented on May 13, 2024

    @jackson-dahl42

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions