def py_encode(symb2freq):
 heap = [[wt, [sym, u'']] for (sym, wt) in symb2freq.items()]
 heapify(heap)
 while (len(heap) > 1):
  lo = heappop(heap)
  hi = heappop(heap)
  for pair in lo[1:]:
   pair[1] = (u'0' + pair[1])
  for pair in hi[1:]:
   pair[1] = (u'1' + pair[1])
  heappush(heap, (([(lo[0] + hi[0])] + lo[1:]) + hi[1:]))
 return dict(heappop(heap)[1:])

def py_encode ( symb2freq ) : heap = [ [ wt , [ sym , u'' ] ] for ( sym , wt ) in symb2freq . items ( ) ] heapify ( heap ) while ( len ( heap ) > 1 ) : lo = heappop ( heap ) hi = heappop ( heap ) for pair in lo [ 1 : ] : pair [ 1 ] = ( u'0' + pair [ 1 ] ) for pair in hi [ 1 : ] : pair [ 1 ] = ( u'1' + pair [ 1 ] ) heappush ( heap , ( ( [ ( lo [ 0 ] + hi [ 0 ] ) ] + lo [ 1 : ] ) + hi [ 1 : ] ) ) return dict ( heappop ( heap ) [ 1 : ] )
huffman encode the given dict mapping symbols to weights from rosetta code .