66 lines
2.6 KiB
Python
Raw Normal View History

2023-05-25 00:39:59 +02:00
#
# Sam Hadow - Huffman-py
# Copyright (C) 2023
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from huffman_py.fonctions.occurence import *
from huffman_py.fonctions.calcul_code import *
from huffman_py.fonctions.affichage_binaire import *
from huffman_py.Sommets import Sommets
from huffman_py.Arbre import Arbre
def huffman_encode(the_data):
lettres_et_occurences = calcul_occurence(the_data)
# affichage des lettres et occurences associées (vérification bon fonctionnement)
les_lettres = lettres_et_occurences.keys()
les_occurences = lettres_et_occurences.values()
print("lettres: ", les_lettres)
print("occurences: ", les_occurences)
les_sommets = []
# conversion des lettres et occurences en sommets
for lettres in les_lettres:
les_sommets.append(Sommets(lettres_et_occurences.get(lettres), lettres))
while len(les_sommets) > 1:
# tri des sommets par ordre croissant
les_sommets = sorted(les_sommets, key = lambda x: x.occurrence)
#for node in les_sommets:
# print(node.lettres, node.occurrence)
# on récupère les 2 plus petits sommets
left = les_sommets[0]
right = les_sommets[1]
left.code = 0
right.code = 1
# on combine les 2 sommets précédents
nouveau_sommet = Sommets(left.occurrence + right.occurrence, left.lettres + right.lettres, left, right)
#nouveau_sommet = Sommets(left.occurrence + right.occurrence, 'a', left, right)
les_sommets.remove(left)
les_sommets.remove(right)
les_sommets.append(nouveau_sommet)
mon_arbre = Arbre(les_sommets[0])
huffmanEncoding = calcul_code(les_sommets[0])
print("lettres avec codes", huffmanEncoding)
encodedOutput = affichage_binaire(the_data,huffmanEncoding)
return encodedOutput, les_sommets[0], huffmanEncoding