Skip to content

Instantly share code, notes, and snippets.

@mightbesimon
Created April 3, 2020 12:41
Show Gist options
  • Save mightbesimon/02acf8f4f023027ccfcc6c5d8420d922 to your computer and use it in GitHub Desktop.
Save mightbesimon/02acf8f4f023027ccfcc6c5d8420d922 to your computer and use it in GitHub Desktop.
Huffman character encoding/decoding
letter = {
'A': '00',
'E': '11',
'T': '010',
'C': '0110',
'L': '0111',
'S': '1000',
'R': '1011',
'O': '10010',
'I': '10011',
'N': '101000',
'F': '101001',
'H': '101010',
'D': '101011',
}
def encode(word):
word = word.upper()
code = [letter[ltr] for ltr in word]
return ''.join(code)
def decode(code):
idx = 0
word = ''
while idx < len(code):
found = []
l = 2
while not any(found):
found = [key for key in letter if letter[key] == code[idx:idx+l]]
l += 1
word += found[0]
idx = idx + l - 1
return word
# example:
if __name__ == '__main__':
print(decode('01101010100111100101011100111010001100101000101011000110110101001010100011'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment