Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
huffman codering voorbeeld op wikipedia
from copy import deepcopy
letters = {'A': (7.49,dict()), 'Z': (1.39,dict()), 'E': (18.91,dict()), 'R': (6.41,dict()), 'T': (6.79,dict()), 'Y': (0.03,dict()), 'U': (1.99,dict()), 'I': (6.50,dict()), 'O': (6.06,dict()), 'P': (1.57,dict()), 'Q': (0.01,dict()), 'S': (3.73,dict()), 'D': (5.93,dict()), 'F': (0.81,dict()), 'G': (3.40,dict()), 'H': (2.38,dict()), 'J': (1.46,dict()), 'K': (2.25,dict()), 'L': (3.57,dict()), 'M': (2.21,dict()), 'W': (1.52,dict()), 'X': (0.04,dict()), 'C': (1.24,dict()), 'V': (2.85,dict()), 'B': (1.58,dict()), 'N': (10.03,dict())}
alfabet = "AZERTYUIOPQSDFGHJKLMWXCVBN"
while len(letters) > 1:
let = sorted(letters, key=lambda x: letters[x][0], reverse=True)
a, b = let[-1], let[-2]
a_, b_ = letters[a], letters[b]
som = a_[0] + b_[0]
del letters[a]
del letters[b]
letters[f"{a}{b}"] = (som, {a: a_, b: b_})
print(letters)
for letter in alfabet:
s, i, tr = deepcopy(letters), "", True
while len(s):
t = list(s.keys())[0]
if letter in t:
s = s[t][1]
i = i + ("1" if tr else "0")
tr = True
else:
del s[t]
tr = False
print(f'{letter}: {i[1:]}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.