Commit 2020391e authored by Pierre-antoine Comby's avatar Pierre-antoine Comby

ajout décodage

parent ea5d40f7
......@@ -17,19 +17,6 @@ class Noeud(object):
return self.p<other.p
def __repr__(self):
return self.name
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)
def create_tree(table_noeud):
queue = table_noeud.copy()
while len(queue) > 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)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment