Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Created April 3, 2017 12:56
Show Gist options
  • Select an option

  • Save rupalbarman/a10ef18136a04ce4d4163c25d6c0a34d to your computer and use it in GitHub Desktop.

Select an option

Save rupalbarman/a10ef18136a04ce4d4163c25d6c0a34d to your computer and use it in GitHub Desktop.
Huffman encoding of strings but without TREES!
from collections import Counter
s= input()
c= Counter(s)
cc= sorted(c.items(), key= lambda x: x[1], reverse= True)
huff_map= {}
a, b= '0', '1'
for x in range(len(cc)-1):
huff_map[cc[x][0]]= a*x + b #assigns 0, 01, 001 to n-1 chars
huff_map[cc[x+1][0]]= a* (len(cc)-1) #assigns 000..0 to nth char
print(huff_map) #prints the huffman mapping
for i in s:
print(huff_map[i], end='') #prints 010101..100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment