Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Python encoding/decoding for huffman tree

1. ## Python encoding/decoding for huffman tree

Hi guys,
I have an assignment for python in my class on Huffman Tree encode and decoding.
I have problems creating my tree right now.
the print statemnts are just for me to see whats running in my function so ignore those. but this is my code so far
class HuffmanNode(object): #parent inheritence?

def __init__(self, left=None, right=None, root=None):
self.left = left
self.right = right
self.root = root
-----------------------------------------------^ thats my huffman node class within this huffman tree class

p = PriorityQueue()
print frequencies

index = 0
for value in frequencies:
if value != 0:
print value
print index
index = index + 1

tup = ()
for i in range(len(frequencies)):
if frequencies[i] != 0:
tup = (i, frequencies[i])
n = self.HuffmanNode(None, None, tup)
p.insert(n, frequencies[i]) #inserted node, freq value
print '----------------------------------------------------------'
# print node.root,node.left,node.right #root =2
total = 0
while not p.is_empty():
a = p.get_min()
if self._root == None:
a = self.HuffmanNode()

a2 = p.get_min()
total = a.root[1], a2.root[1]
node = self.HuffmanNode(a, a2, total)

print a.root
print a.left
print a.right

i faollowed wikis steps "The simplest construction algorithm uses a priority queue where the node with lowest probability is given highest priority:

Create a leaf node for each symbol and add it to the priority queue.
While there is more than one node in the queue:
Remove the two nodes of highest priority (lowest probability) from the queue
Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.
Add the new node to the queue.
The remaining node is the root node and the tree is complete.
"

I am supposed to manually remove first two nodes , then every other node only removes one by one . but i cant seem to get it to work, how do i remove the firsti two without having the whileeloop become taking two nodes every pass
i trid using an iff statement but i dont know if my iff statement condition is right.