From 901cc818bc076e21139159b4ad51ee991b697806 Mon Sep 17 00:00:00 2001 From: shockrahwow Date: Sun, 5 May 2019 21:12:35 -0700 Subject: [PATCH] huffman decoder --- 370/homework/huff.py | 31 +++++++++++++++++++++++++++++++ 370/homework/huffman.py | 32 +++++++++++++++++++++----------- 2 files changed, 52 insertions(+), 11 deletions(-) create mode 100644 370/homework/huff.py diff --git a/370/homework/huff.py b/370/homework/huff.py new file mode 100644 index 0000000..cead790 --- /dev/null +++ b/370/homework/huff.py @@ -0,0 +1,31 @@ +class Node(): + def __init__(self, c, weight): + self.c = c + self.freq = weight + self.left = None + self.right = None + + def __repr__(self): + return f'{self.c}|{self.freq}' + +class Huffman: + def __init__(self, string): + self.heap = [] + self.charMap = self.charFrequencies(string) + + def charFrequencies(self, string): + ret = [] + for i in string: + if i in ret: + ret[i] += 1 + else: + ret[i] = 1 + return ret.sort() + +if __name__ == '__main__': + text = input() + binary = input() + + # encode the first given string to build a tree from it + huff = Huffman(text) + print(huff.charMap) \ No newline at end of file diff --git a/370/homework/huffman.py b/370/homework/huffman.py index e427916..9e55470 100644 --- a/370/homework/huffman.py +++ b/370/homework/huffman.py @@ -2,12 +2,12 @@ import queue class Node(): def __init__(self, c, weight): self.c = c - self.weight = weight + self.freq = weight self.left = None self.right = None def __repr__(self): - return f'{self.c}|{self.weight}' + return f'{self.c}|{self.freq}' class MinHeap(): def __init__(self): @@ -58,12 +58,16 @@ class MinHeap(): self.__heapifyDown(mini) def printChar(self, c): - # Traverse through the tree until we get to a leaf then back out - tmp = self.data[0] - # keep going until we hit a leaf - while tmp.left is not None or tmp.right is not None: - # 0 if left : 1 if right - continue + # TODO: this method + curr = self.data[0] + for i in bin: + if i == '1' and curr.right is not None: + curr = curr.right + if i == '0' and curr.left is not None: + curr = curr.left + + + def main(): @@ -97,10 +101,10 @@ def frequencyMap(string): # otherwise increment the frequency of that node for k in ret: if k.c == i: - k.weight += 1 + k.freq += 1 # Sort the charmap based on the frequencies - ret.sort(key=lambda x: x.weight) + ret.sort(key=lambda x: x.freq) return ret @@ -110,9 +114,15 @@ def buildMinHeap(freqs): while _queue.qsize() >= 2: left = _queue.get() right = _queue.get() - weight = left.weight + right.weight + weight = left.freq+ right.freq root = Node('*', weight) + + # insert the new sub-tree into the minheap and add the tree to the queue + heap.insert(root) + _queue.put(root) + # Once there is one item in the queue left we can simply return the new thing + heap.print() return heap