Commit d77a10db authored by Hugo Geoffroy's avatar Hugo Geoffroy

Ajout du notebook sur la Compression de Huffman

parent f900c100
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Encodage de Huffman"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comptage des symboles"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {},
"outputs": [],
"source": [
"from collections import defaultdict\n",
"from typing import Dict, List\n",
"from operator import itemgetter"
]
},
{
"cell_type": "code",
"execution_count": 167,
"metadata": {},
"outputs": [],
"source": [
"def compter_symboles(texte: str) -> Dict[str, int]:\n",
" symboles = defaultdict(int)\n",
" for symbole in texte:\n",
" symboles[symbole] += 1\n",
" return symboles"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [],
"source": [
"def compter_symboles_récursion(texte: str) -> Dict[str, int]:\n",
" if len(texte) == 0:\n",
" return {}\n",
" symboles = compter_symboles_récursion(texte[:-1])\n",
" symboles[texte[-1]]= symboles.get(texte[-1], 0) + 1\n",
" return symboles"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [],
"source": [
"#def compter_symboles(texte: str) -> Dict[str, int]:\n",
"# occurrences = {}\n",
"# for caractère in texte:\n",
"# occurrences_du_caractère = occurrences.get(caractère, 0)\n",
"# occurrences[caractère] = occurrences_du_caractère + 1\n",
"# return occurrences"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"defaultdict(int,\n",
" {' ': 3,\n",
" 'f': 2,\n",
" 'i': 2,\n",
" 'j': 2,\n",
" 'm': 1,\n",
" 'o': 6,\n",
" 'r': 6,\n",
" 's': 3,\n",
" 't': 2,\n",
" 'u': 6})"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"compter_symboles_itération(\"toujours mourir toujours souffrir\")"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{' ': 3,\n",
" 'f': 2,\n",
" 'i': 2,\n",
" 'j': 2,\n",
" 'm': 1,\n",
" 'o': 6,\n",
" 'r': 6,\n",
" 's': 3,\n",
" 't': 2,\n",
" 'u': 6}"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"compter_symboles_récursion(\"toujours mourir toujours souffrir\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Table de Huffman"
]
},
{
"cell_type": "code",
"execution_count": 219,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Bonjour Jean, je suis Paul.'"
]
},
"execution_count": 219,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"'Bonjour {}, je suis {}.'.format('Jean', 'Paul')"
]
},
{
"cell_type": "code",
"execution_count": 220,
"metadata": {},
"outputs": [],
"source": [
"def générer_table(symboles: Dict[str, int]) -> Dict[str, List[bool]]:\n",
" accumulateur = [(occurrences, [(symbole, \"\")])\n",
" for symbole, occurrences \n",
" in symboles.items()]\n",
" while len(accumulateur) > 1:\n",
" print(accumulateur)\n",
" # Trier la liste\n",
" accumulateur.sort(reverse=True)\n",
" # Sortir deux élements\n",
" occurrences, paires = accumulateur.pop()\n",
" _occurrences, _paires = accumulateur.pop()\n",
" # Modifier ces élements\n",
" paires = [(symbole, '0{}'.format(code)) for symbole, code in paires]\n",
" _paires = [(symbole, '1{}'.format(code)) for symbole, code in _paires]\n",
" # Insérer la combinaison de ces élements\n",
" accumulateur.append(\n",
" (occurrences + _occurrences, paires + _paires)\n",
" )\n",
" return dict(accumulateur[0][1])"
]
},
{
"cell_type": "code",
"execution_count": 221,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(1, [('t', '')]), (1, [('s', '')]), (1, [('j', '')]), (2, [('u', '')]), (1, [('r', '')]), (2, [('o', '')])]\n",
"[(2, [('u', '')]), (2, [('o', '')]), (1, [('t', '')]), (1, [('s', '')]), (2, [('j', '0'), ('r', '1')])]\n",
"[(2, [('u', '')]), (2, [('o', '')]), (2, [('j', '0'), ('r', '1')]), (2, [('s', '0'), ('t', '1')])]\n",
"[(2, [('u', '')]), (2, [('s', '0'), ('t', '1')]), (4, [('j', '00'), ('r', '01'), ('o', '1')])]\n",
"[(4, [('j', '00'), ('r', '01'), ('o', '1')]), (4, [('s', '00'), ('t', '01'), ('u', '1')])]\n"
]
},
{
"data": {
"text/plain": [
"{'j': '000', 'o': '01', 'r': '001', 's': '100', 't': '101', 'u': '11'}"
]
},
"execution_count": 221,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"générer_table(compter_symboles_itération(\"toujours\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Encodage/décodage"
]
},
{
"cell_type": "code",
"execution_count": 194,
"metadata": {},
"outputs": [],
"source": [
"def encoder(texte, table):\n",
" return [table[caractère] for caractère in texte]\n",
"\n",
"def décoder(données, table):\n",
" table_inverse = {code: symbole for symbole, code in table.items()}\n",
" return ''.join(table_inverse[code] for code in données)"
]
},
{
"cell_type": "code",
"execution_count": 204,
"metadata": {},
"outputs": [],
"source": [
"table = générer_table(compter_symboles(\"Bonjour !\"))"
]
},
{
"cell_type": "code",
"execution_count": 197,
"metadata": {},
"outputs": [],
"source": [
"message = encoder(\"Bonjour !\", table)"
]
},
{
"cell_type": "code",
"execution_count": 199,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Bonjour !'"
]
},
"execution_count": 199,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"décoder(message, table)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Mesures de compression"
]
},
{
"cell_type": "code",
"execution_count": 212,
"metadata": {},
"outputs": [],
"source": [
"def mesurer_compression(texte, table):\n",
" _table = générer_table(compter_symboles(texte))\n",
" message = encoder(texte, table)\n",
" _message = encoder(texte, _table)\n",
" return sum(map(len, _message)) / sum(map(len, message))"
]
},
{
"cell_type": "code",
"execution_count": 214,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.45454545454545453"
]
},
"execution_count": 214,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mesurer_compression(\"B !\", table)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
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