2

I'm trying to implement Huffman's Coding algorithm in python but when I try to add node data in the tree I'm not getting the correct output values?

Here is the code that I have so far for adding the nodes:

 n = 6
 charArray = ['a','b','c','d','e','f']  
 charFreq = [45,13,12,16,9,5]
 Heap = []

 for i in range(0, n):
     lol = HuffmanNode()
     lol.setDataC(charFreq[i], charArray[i])

     lol.left = None
     lol.right = None
     heapq.heappush(Heap, lol)

 root = HuffmanNode()
 root = None

 while (len(Heap) > 1):
     x = HuffmanNode()
     x = heappeak(Heap)
     heapq.heappop(Heap)
     print("X data")
     print(x.data)

     y = HuffmanNode()
     y = heappeak(Heap)
     heapq.heappop(Heap)
     print("Y data")
     print(y.data)

     f =  HuffmanNode()
     f.data = x.data + y.data
     print("f data")
     print(f.data)
     f.c = '-'

     f.left = x
     f.right = y
     root = f

     heapq.heappush(Heap, f)

And I get the output:

X data
5
Y data
9
f data
14
X data
14
Y data
16
f data
30
X data
30
Y data
12
f data
42
X data
42
Y data
13
f data
55
X data
55
Y data
45
f data
100
f:00000
e:00001
d:0001
c:001
b:01
a:1

When it should be:

X data
5
Y data
9
f data
14
X data
12
Y data
13
f data
25
X data
14
Y data
16
f data
30
X data
25
Y data
30
f data
55
X data
45
Y data
55
f data
100
a:0
c:100
b:101
f:1100
e:1101
d:111

For some reason it's reading 14 again in the heap and no idea why? Any help would be great

user58697
  • 7,808
  • 1
  • 14
  • 28
Richard Desouza
  • 249
  • 4
  • 13
  • What is `heappeak(Heap)`?([`heapq.heappop(heap)`](https://docs.python.org/library/heapq.html#heapq.heappop) already returns the top priority value.) (Why assign freshly instantiated `HuffmanNode`s to `x` and `y` to immediately overwrite them with `heappeak(Heap)`?) – greybeard Nov 22 '19 at 03:42
  • Please show the definition of `HuffmanNode`: how do two `HuffmanNode`s compare? – greybeard Nov 22 '19 at 04:05
  • Yea it was a compare problem i had it as a.data - b.data when it should have been a.data < b.data. Everything works fine now thanks though! – Richard Desouza Nov 23 '19 at 04:08
  • 2
    For this question to be useful for others, please show the definition of `HuffmanNode`. Where does the output with the colons come from? Consider [answering your own question](https://stackoverflow.com/help/badges/14/self-learner). – greybeard Nov 23 '19 at 05:40
  • 2
    (If you wanted to know if there was something to improve in your code, consider posting to [Code Review@SE](https://codereview.stackexchange.com/help/on-topic) - invest diligence to [get the best value out of Code Review](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions).) – greybeard Nov 23 '19 at 05:49

0 Answers0