Skip to content

Instantly share code, notes, and snippets.

@st0le
Last active May 19, 2017 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st0le/a4efe0295b83e2bcae5f005195362561 to your computer and use it in GitHub Desktop.
Save st0le/a4efe0295b83e2bcae5f005195362561 to your computer and use it in GitHub Desktop.
Py3
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