ajout décodage

This commit is contained in:
Pierre-antoine Comby 2019-02-11 14:16:58 +01:00
parent ea5d40f7f3
commit 2020391ee8

View file

@ -17,19 +17,6 @@ class Noeud(object):
return self.p<other.p return self.p<other.p
def __repr__(self): def __repr__(self):
return self.name 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): def create_tree(table_noeud):
queue = table_noeud.copy() queue = table_noeud.copy()
while len(queue) > 2: while len(queue) > 2:
@ -40,19 +27,21 @@ def create_tree(table_noeud):
queue.append(Noeud(left=l,right=r)) queue.append(Noeud(left=l,right=r))
root= Noeud(left=queue[0],right=queue[1]) root= Noeud(left=queue[0],right=queue[1])
return root return root
root_node= create_tree(table_noeud)
print(root_node)
def gen_code(node,prefix=''): def gen_code(node,prefix=''):
def gen_code_rec(node,prefix=''):
if node.left != None: if node.left != None:
node.code = prefix node.code = prefix
gen_code(node.left,prefix+'0') t_1 = gen_code(node.left,prefix+'0')
gen_code(node.right,prefix+'1') t_2 = gen_code(node.right,prefix+'1')
return [*t_1,*t_2]
else: else:
node.code = prefix node.code = prefix
print(node.name,node.code) return (node.name,node.code)
gen_code(root_node) x = gen_code_rec(node,prefix)
return x
def draw_tree(node): def draw_tree(node):
if len(node.name) == 1: # feuille if len(node.name) == 1: # feuille
@ -65,6 +54,7 @@ def draw_tree(node):
desc += 'N{}:s -> N{}:e;\n'.format(node.code,node.right.code) desc += 'N{}:s -> N{}:e;\n'.format(node.code,node.right.code)
return desc return desc
def make_tree():
with open('graph.dot','w') as f: with open('graph.dot','w') as f:
f.write('digraph G {\n ') f.write('digraph G {\n ')
f.write(' splines=ortho \n') f.write(' splines=ortho \n')
@ -74,3 +64,34 @@ with open('graph.dot','w') as f:
f.write('}') f.write('}')
subprocess.call('dot -Tpng graph.dot -o graph.png', shell=True) subprocess.call('dot -Tpng graph.dot -o graph.png', shell=True)
print('done') 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)