63 lines
2.2 KiB
Python
Raw Normal View History

2023-05-25 02:08:43 +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.functions.occurence import *
from huffman_py.functions.calculate_code import *
from huffman_py.functions.print_binary import *
from huffman_py.Node import Node
from huffman_py.Tree import Tree
def huffman_encode(the_data):
char_and_occurences = calcul_occurence(the_data)
# log char and occurences
the_char = char_and_occurences.keys()
the_occurences = char_and_occurences.values()
print("char: ", the_char)
print("occurences: ", the_occurences)
the_nodes = []
# convert char and occurences in nodes
for char in the_char:
the_nodes.append(Node(char_and_occurences.get(char), char))
while len(the_nodes) > 1:
# sort nodes
the_nodes = sorted(the_nodes, key = lambda x: x.occurrence)
# get the 2 smallest nodes
left = the_nodes[0]
right = the_nodes[1]
left.code = 0
right.code = 1
# Merge these 2 nodes
new_node = Node(left.occurrence + right.occurrence, left.char + right.char, left, right)
the_nodes.remove(left)
the_nodes.remove(right)
the_nodes.append(new_node)
my_tree = Tree(the_nodes[0])
huffmanEncoding = calculate_code(the_nodes[0])
print("char avec codes", huffmanEncoding)
encodedOutput = print_binary(the_data,huffmanEncoding)
return encodedOutput, the_nodes[0], huffmanEncoding