How can I create a tree for Huffman encoding and decoding?

前端 未结 5 1914
轮回少年
轮回少年 2021-02-05 21:04

For my assignment, I am to do a encode and decode for huffman trees. I have a problem creating my tree, and I am stuck.

Don\'t mind the print statements - they are just

5条回答
  •  庸人自扰
    2021-02-05 21:21

    @Dave class HuffmanNode(object) has a subtle bug. When the two frequencies are equal an exception is thrown: For example let

        freq = [ (200/3101, 'd'), (100/3101, 'e'), (100/3101, 'f') ]
    

    Then you get TypeError: unorderable types: HuffmanNode() < str(). The problem has to do with the PriorityQueue implementation. I suspect when the first elements of the tuples compare equal, PriorityQueue wants to compare the second elements one of which is a python object. You add the lt method to your class and the problem is solved.

        def __lt__(self,other):
            return 0
    

提交回复
热议问题