Created
April 3, 2017 12:56
-
-
Save rupalbarman/a10ef18136a04ce4d4163c25d6c0a34d to your computer and use it in GitHub Desktop.
Huffman encoding of strings but without TREES!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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