def build_huffman_tree(freq_table, arity_exp): ''' Build the huffman tree for the input textfile and return a stack (maybe along with the character at the root node) Algo: (i) Start by making a heap out of freq_table using modheap (ii) Pop two elements out of the heap at a time (iii) Form a composite character that is the concatenation of the two and the combined frequency of the two (iv) Add the new composite character with its frequency to the heap (v) Add the two popped elements to a stack - simply append to a list Elements of the stack are of the form (element, frequency, parent, additional_code_bit) (vi) Repeat the above four steps till the heap has only the root element left (vii) Return the stack along with the top root element of the heap ''' modheap.initialize_heap(True,arity_exp,cmp_freq) modheap.DATA=freq_table.values() list0=freq_table.items() stack=[] i=0 while(len(modheap.DATA)>1): n=0 m=0 modheap.heapify() print modheap.DATA a=modheap.pop() b=modheap.pop() for letter,frequency in list0: if(frequency==a): a1=letter k1=n else: n=n+1 if(frequency==b): b1=letter k2=m else: m=m+1 if(k2<k1): del list0[k1] del list0[k2] if(k2>k1): del list0[k2] del list0[k1] list0.append((a1+b1,a+b)) stack=stack+[(a1,a,0)]+[(b1,b,1)] dict2=dict(list0) modheap.DATA=dict2.values() modheap.DATA=stack pi=modheap.get_parent_index(i) data=[] while(i<=len(stack)-1): if(pi!=None): data=data+[stack[i][:-1]+(stack[pi][0],)+(stack[i][-1],)] if(pi==None): data=data+[stack[i][:-1]+('None',)+(stack[i][-1],)] i=i+1 pi=modheap.get_parent_index(i) return data
def test_noparent(self, ismin, heapsize, aexp, parent, child): ''' Test if the functions correctly recognize the root of the heap (with no parent) ''' modheap.initialize_heap(ismin, aexp, CMP_FUNCTION) modheap.import_list(self.nlist(heapsize)) self.assertEqual(parent, modheap.get_parent_index(child))
def test_indices(self, ismin, heapsize, aexp, parent, child): ''' Test max elements of the heap ''' modheap.initialize_heap(ismin, aexp, CMP_FUNCTION) modheap.import_list(self.nlist(heapsize)) self.assertEqual(child, modheap.get_leftmostchild_index(parent)) self.assertEqual(parent, modheap.get_parent_index(child))