UNB/ CS/ David Bremner/ teaching/ cs3383/ lectures/ 20.0-demos/ huffman.py
#!/usr/bin/env python3
from print_tree import print_tree
from heapq import heappush,heappop

def huffman(f):
  tree=[]; H=[]; n = len(f)
  for i in range(0,n):
      heappush(H,(f[i],i))
      tree.append((f[i],None,None))
  for k in range(n,2*n-1):
      (f1,index1) = heappop(H)
      (f2,index2) = heappop(H)
      f3 = f1 + f2
      heappush(H,(f3,k))
      tree.append((f3,index1,index2))
  return tree

if __name__ == "__main__":
    f = [3, 20, 23, 37, 60, 70]
    tree = huffman(f)

    print_tree(tree)