import heapq 
from collections import Counter 
 
def huffman_coding(text): 
    freq = Counter(text) 
    heap = [[w, [ch, ""]] for ch, w in freq.items()] 
    heapq.heapify(heap) 
 
    while len(heap) > 1: 
        lo, hi = heapq.heappop(heap), heapq.heappop(heap) 
        for p in lo[1:]: p[1] = '0' + p[1] 
        for p in hi[1:]: p[1] = '1' + p[1] 
        heapq.heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) 
 
    codes = dict(heap[0][1:]) 
    encoded = ''.join(codes[c] for c in text) 
    decoded, temp = '', '' 
    rev = {v: k for k, v in codes.items()} 
    for bit in encoded: 
        temp += bit 
        if temp in rev: 
            decoded += rev[temp] 
            temp = "" 
    orig_size, enc_size = len(text)*8, sum(len(c)*freq[ch] 
for ch, c in codes.items()) 
    saved = orig_size - enc_size 
    print("\n--- Huffman Codes ---") 
    [print(f"{ch}: {codes[ch]}") for ch in codes] 
    print(f"\nEncoded: {encoded}\nDecoded: {decoded}") 
    print(f"\nOriginal: {orig_size} bits | Encoded: {enc_size} bits | Saved: {saved} bits ({saved/orig_size*100:.2f}%)") 
if __name__ == "__main__": 
    huffman_coding(input("Enter text: ")) 