def build_codec(freq_list): """ Purpose: Build a dictionary containing character:code pairs from the frequency list. Pre-conditions: :param freq_list: A list of (frequency,character) pairs. Return: :return: a dictionary """ def get_frequency(a_HuffmanTree): """ helper function for sorting the list according to frequency of the char :param a_HuffmanTree: :return: """ return a_HuffmanTree.get_freq() leafs = [HT.HuffmanTree(freq=f, char=c) for c,f in freq_list] leafs.sort(key=get_frequency) heap = HP.HuffmanHeap(leafs, []) while len(heap.old) != 0: temp1 = heap.dequeue() temp2 = heap.dequeue() item3 = HT.HuffmanTree(temp1.get_freq()+temp2.get_freq(),left=temp1,right=temp2) heap.enqueue(item3) if len(heap.new) >= 2: while True: temp1 = heap.dequeue() temp2 = heap.dequeue() item3 = HT.HuffmanTree(temp1.get_freq() + temp2.get_freq(), left=temp1, right=temp2) if len(heap.new) == 0: heap.enqueue(item3) break heap.enqueue(item3) return heap.new[0].build_codec()
def build_codec(freq_list): """ Purpose: Build a dictionary containing character:code pairs from the frequency list. Pre-conditions: :param freq_list: A list of (character,frequency) pairs. Return: :return: a dictionary """ # sort the frequency list freq_list.sort(key=lambda p: p[1]) # create the queue of Huffman trees # note: a new ADT for this purpose! hq = HH.HuffmanHeap([HT.HuffmanTree(freq=f, char=c) for c, f in freq_list]) # dequeue 2 trees, combine them, and enqueue the resulting tree while len(hq) > 1: t1 = hq.dequeue() t2 = hq.dequeue() hq.enqueue(HT.HuffmanTree(left=t1, right=t2)) #build a codec from the only tree that's left survivor = hq.dequeue() return survivor.build_codec()