Skip to content

Instantly share code, notes, and snippets.

@bedekelly
Created March 22, 2015 15:37
Show Gist options
  • Save bedekelly/67dd9fc729dc204a05d3 to your computer and use it in GitHub Desktop.
Save bedekelly/67dd9fc729dc204a05d3 to your computer and use it in GitHub Desktop.
Building a Huffman Coding Tree using Python
#!/usr/bin/env python3
from pprint import pprint
def main():
text = input()
forest = []
for letter in text:
for tree in forest:
if tree["letter"] == letter:
break
else:
forest.append({"letter": letter,
"text": text,
"weight": text.count(letter)})
forest = sorted(forest, key=lambda i:i["weight"])
while len(forest) > 2:
t1, t2, *rest = forest
new_tree = {}
new_tree["weight"] = t1["weight"] + t2["weight"]
new_tree["left"] = t1
new_tree["right"] = t2
rest.append(new_tree)
forest = rest
forest = sorted(forest, key=lambda i:i["weight"])
t1, t2 = forest
tree = {}
tree["weight"] = t1["weight"] + t2["weight"]
tree["left"] = t1
tree["right"] = t2
pprint(tree)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment