Skip to content

Instantly share code, notes, and snippets.

@jimbob88
Created October 25, 2022 12:21
Show Gist options
  • Save jimbob88/7d7cf46a036775a5a43d313e9f3178b3 to your computer and use it in GitHub Desktop.
Save jimbob88/7d7cf46a036775a5a43d313e9f3178b3 to your computer and use it in GitHub Desktop.
Huffman Coding in Python
"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
"""
from dataclasses import dataclass
from typing import Tuple, Union, List, Dict
from collections import Counter
@dataclass
class Node:
left: Union["Node", None]
right: Union["Node", None]
freq: int
char: Union[str, None]
def sort_nodes(nodes: List[Node]) -> List[Node]:
return list(sorted(nodes, key=lambda x: x.freq))
def huffman_tree(string: str) -> Node:
counts = Counter(string)
nodes = [Node(None, None, count, char) for char, count in counts.items()]
sorted_nodes = sort_nodes(nodes)
while len(sorted_nodes) > 1:
left = sorted_nodes.pop(0)
right = sorted_nodes.pop(0)
sorted_nodes.append(
Node(left, right, left.freq + right.freq, None)
)
sorted_nodes = sort_nodes(sorted_nodes)
return sorted_nodes[0]
def huffman_table(tree: Node, left="0", right="1") -> Dict[str, str]:
stack: List[Tuple[Node, str]] = [(tree, "")]
table: Dict[str, str] = {}
while stack:
node, parent = stack.pop()
if node.left is not None:
stack.append((node.left, parent + left))
if node.right is not None:
stack.append((node.right, parent + right))
if node.char and node.left is None and node.right is None:
table[node.char] = parent
return table
def encode(table: Dict[str, str], string: str):
for char in string:
yield table[char]
def decode(tree: Node, encoded: str, left="0"):
node = tree
for char in encoded:
node = node.left if char == left else node.right
if node.char is not None:
yield node.char
node = tree
def example():
test_string = "this is an example for huffman encoding"
tree = huffman_tree(test_string)
table = huffman_table(tree)
encoded = ''.join(encode(table, test_string))
print(encoded)
decoded = ''.join(decode(tree, encoded))
print(decoded)
if __name__ == '__main__':
example()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment