Last active
May 19, 2017 00:00
-
-
Save st0le/a4efe0295b83e2bcae5f005195362561 to your computer and use it in GitHub Desktop.
Py3
This file contains 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 | |
from heapq import heapify, heappop, heappush | |
s = input() | |
c = Counter(s) | |
pq = [(c[k], k, None, None) for k in c] | |
codes = {} | |
heapify(pq) | |
while len(pq) > 1: | |
r = heappop(pq) | |
l = heappop(pq) | |
heappush(pq, (l[0] + r[0], l[1] + r[1], l, r)) | |
def buildCodes(parent, code): | |
if parent: | |
if len(parent[1]) == 1: | |
codes[parent[1]] = code | |
buildCodes(parent[2], code + '0') | |
buildCodes(parent[3], code + '1') | |
buildCodes(pq[0], '') | |
print(codes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment