def build_tree(lengths):
 max_length = (max(lengths) + 1)
 bit_counts = ([0] * max_length)
 next_code = ([0] * max_length)
 tree = {}
 for i in lengths:
  if i:
   bit_counts[i] += 1
 code = 0
 for i in xrange(1, len(bit_counts)):
  next_code[i] = code = ((code + bit_counts[(i - 1)]) << 1)
 for (i, ln) in enumerate(lengths):
  if ln:
   tree[(ln, next_code[ln])] = i
   next_code[ln] += 1
 return tree

def build_tree ( lengths ) : max_length = ( max ( lengths ) + 1 ) bit_counts = ( [ 0 ] * max_length ) next_code = ( [ 0 ] * max_length ) tree = { } for i in lengths : if i : bit_counts [ i ] += 1 code = 0 for i in xrange ( 1 , len ( bit_counts ) ) : next_code [ i ] = code = ( ( code + bit_counts [ ( i - 1 ) ] ) << 1 ) for ( i , ln ) in enumerate ( lengths ) : if ln : tree [ ( ln , next_code [ ln ] ) ] = i next_code [ ln ] += 1 return tree
build a huffman tree from a list of lengths .