diff --git a/455-Codage_Sources/algo_code/huffman2.py b/455-Codage_Sources/algo_code/huffman2.py index 1cbb49d..d9c21ae 100755 --- a/455-Codage_Sources/algo_code/huffman2.py +++ b/455-Codage_Sources/algo_code/huffman2.py @@ -17,19 +17,6 @@ class Noeud(object): return self.p 2: @@ -40,19 +27,21 @@ def create_tree(table_noeud): queue.append(Noeud(left=l,right=r)) root= Noeud(left=queue[0],right=queue[1]) return root -root_node= create_tree(table_noeud) -print(root_node) + def gen_code(node,prefix=''): - if node.left != None: - node.code = prefix - gen_code(node.left,prefix+'0') - gen_code(node.right,prefix+'1') - else: - node.code = prefix - print(node.name,node.code) + def gen_code_rec(node,prefix=''): + if node.left != None: + node.code = prefix + t_1 = gen_code(node.left,prefix+'0') + t_2 = gen_code(node.right,prefix+'1') + return [*t_1,*t_2] + else: + node.code = prefix + return (node.name,node.code) -gen_code(root_node) + x = gen_code_rec(node,prefix) + return x def draw_tree(node): if len(node.name) == 1: # feuille @@ -65,12 +54,44 @@ def draw_tree(node): desc += 'N{}:s -> N{}:e;\n'.format(node.code,node.right.code) return desc -with open('graph.dot','w') as f: - f.write('digraph G {\n ') - f.write(' splines=ortho \n') - f.write('rankdir=RL;\n') - f.write(draw_tree(root_node)) - f.write('{rank =same; N' + '; N'.join([n.code for n in table_noeud]) +';}\n') - f.write('}') -subprocess.call('dot -Tpng graph.dot -o graph.png', shell=True) -print('done') +def make_tree(): + with open('graph.dot','w') as f: + f.write('digraph G {\n ') + f.write(' splines=ortho \n') + f.write('rankdir=RL;\n') + f.write(draw_tree(root_node)) + f.write('{rank =same; N' + '; N'.join([n.code for n in table_noeud]) +';}\n') + f.write('}') + subprocess.call('dot -Tpng graph.dot -o graph.png', shell=True) + print('done') + + +def decode_huffman(reverse, code): + res ="" + while code: + for k in reverse: + if text.startswith(k): + res +=reverse[k] + text = text[len(k):] + return res + +table = [ + ('A', 25), + ('B', 20), + ('C', 15), + ('D', 12), + ('E', 10), + ('F', 8), + ('G', 5), + ('H', 5)] + +table_noeud = [Noeud(name=x[0],p=x[1]) for x in table] + +print(table_noeud) +root_node= create_tree(table_noeud) +print(root_node) + +x= gen_code(root_node) +reverse_huffman = {x[i+1]:x[i] for i in range(0,len(x)-1,2)} + +print(table_huffman)