Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
26-liner: clean solution in Clear category for Huffman Encode by przemyslaw.daniel
from collections import Counter
from heapq import heapify, heappop, heappush
def huffman_encode(data: str) -> str:
"""
Implementation of huffman coding
:param data: input string
:return: encoded bit string
"""
queue = [pair[::-1] for pair in Counter(data).items()]
result = {character: '' for character in set(data)}
heapify(queue)
while len(queue) > 1:
amount1, chars1 = heappop(queue)
amount2, chars2 = heappop(queue)
for char in chars1:
result[char] += '0'
for char in chars2:
result[char] += '1'
heappush(queue, (amount1 + amount2, chars1 + chars2))
return ''.join(result[char][::-1] or '0' for char in data)
Dec. 13, 2022