def make_weighted_tree(fn, ls, **kwargs):
 if (not ls):
  raise ValueError('Called make_weighted_tree with empty list')
 ls.sort()
 while (len(ls) > 1):
  a = ls.pop(0)
  b = ls.pop(0)
  insort(ls, ((a[0] + b[0]), fn(a[1], b[1])))
 return ls[0][1]

def make_weighted_tree ( fn , ls , ** kwargs ) : if ( not ls ) : raise ValueError ( 'Called make_weighted_tree with empty list' ) ls . sort ( ) while ( len ( ls ) > 1 ) : a = ls . pop ( 0 ) b = ls . pop ( 0 ) insort ( ls , ( ( a [ 0 ] + b [ 0 ] ) , fn ( a [ 1 ] , b [ 1 ] ) ) ) return ls [ 0 ] [ 1 ]
takes a function/class that takes two positional arguments and a list of tuples and returns a huffman-like weighted tree of results/instances .