Skip to content

Instantly share code, notes, and snippets.

View ansegura7's full-sized avatar
:octocat:
Always Coding

Andres Segura-Tinoco ansegura7

:octocat:
Always Coding
View GitHub Profile
@mreid
mreid / huffman.py
Last active September 25, 2021 12:22
Example implementation of Huffman coding in Python
# Example Huffman coding implementation
# Distributions are represented as dictionaries of { 'symbol': probability }
# Codes are dictionaries too: { 'symbol': 'codeword' }
def huffman(p):
'''Return a Huffman code for an ensemble with distribution p.'''
assert(sum(p.values()) == 1.0) # Ensure probabilities sum to 1
# Base case of only two symbols, assign 0 or 1 arbitrarily
if(len(p) == 2):