def collapse_cell_addresses(cells, input_ranges=()):
 keyfunc = (lambda x: x[0])
 raw_coords = [coordinate_from_string(cell) for cell in cells]
 grouped_coords = OrderedDict(((k, [c[1] for c in g]) for (k, g) in groupby(sorted(raw_coords, key=keyfunc), keyfunc)))
 ranges = list(input_ranges)
 for column in grouped_coords:
  rows = sorted(grouped_coords[column])
  grouped_rows = [[r[1] for r in list(g)] for (k, g) in groupby(enumerate(rows), (lambda x: (x[0] - x[1])))]
  for rows in grouped_rows:
   if (len(rows) == 0):
    pass
   elif (len(rows) == 1):
    ranges.append(('%s%d' % (column, rows[0])))
   else:
    ranges.append(('%s%d:%s%d' % (column, rows[0], column, rows[(-1)])))
 return ' '.join(ranges)

def collapse_cell_addresses ( cells , input_ranges = ( ) ) : keyfunc = ( lambda x : x [ 0 ] ) raw_coords = [ coordinate_from_string ( cell ) for cell in cells ] grouped_coords = OrderedDict ( ( ( k , [ c [ 1 ] for c in g ] ) for ( k , g ) in groupby ( sorted ( raw_coords , key = keyfunc ) , keyfunc ) ) ) ranges = list ( input_ranges ) for column in grouped_coords : rows = sorted ( grouped_coords [ column ] ) grouped_rows = [ [ r [ 1 ] for r in list ( g ) ] for ( k , g ) in groupby ( enumerate ( rows ) , ( lambda x : ( x [ 0 ] - x [ 1 ] ) ) ) ] for rows in grouped_rows : if ( len ( rows ) == 0 ) : pass elif ( len ( rows ) == 1 ) : ranges . append ( ( '%s%d' % ( column , rows [ 0 ] ) ) ) else : ranges . append ( ( '%s%d:%s%d' % ( column , rows [ 0 ] , column , rows [ ( - 1 ) ] ) ) ) return ' ' . join ( ranges )
collapse a collection of cell co-ordinates down into an optimal range or collection of ranges .