Created
May 15, 2012 18:25
-
-
Save rubik/2703965 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import itertools | |
import collections | |
def sum_column(data): | |
return sum(zip(*data)[1], 0.0) | |
def split_groups(sensors): | |
sensors.sort(key=lambda item: item[1], reverse=True) | |
per_group = len(sensors) // 12 | |
average = sum_column(sensors) / len(sensors) | |
data = collections.deque(sensors) | |
groups = [[] for i in xrange(12)] | |
cycle = itertools.cycle(groups) | |
try: | |
while True: | |
current = cycle.next() | |
if len(current) == per_group - 1: | |
if sum_column(current) < average: | |
current.append(data.popleft()) | |
else: | |
current.append(data.pop()) | |
continue | |
current.append(data.popleft()) | |
current.append(data.pop()) | |
except IndexError: | |
return groups | |
def split_groups2(sensors): | |
sensors.sort(key=lambda item: item[1], reverse=True) | |
groups = [[] for i in xrange(12)] | |
cycle = itertools.cycle(groups) | |
per_group = int(math.ceil(len(sensors) / 3.)) | |
partitions = [sensors[i:i + per_group] for i in xrange(0, len(sensors) | |
per_group)] | |
medium, low = map(reversed, partitions[1:]) | |
for sensor, value in itertools.chain(partitions[0], medium, low): | |
cycle.next().append((sensor, value)) | |
return groups | |
def format_groups(result): | |
ret = [] | |
for group in result: | |
tmp = [] | |
tmp.append('\n'.join('{0} {1}'.format(k, v) for k, v in group)) | |
tmp.append(' ' * 8 + str(int(sum_column(group)))) | |
ret.append('\n'.join(tmp)) | |
return '\n\n'.join(ret) | |
if __name__ == '__main__': | |
import sys | |
implementation = split_groups | |
if '--second' in sys.argv: | |
sys.argv.remove('--second') | |
implementation = split_groups2 | |
with open(sys.argv[1]) as fobj: | |
sensors = [] | |
for line in fobj: | |
sensor, value = line.strip().split(', ') | |
sensors.append((sensor, int(value))) | |
sys.stdout.write(format_groups(split_groups(sensors))) | |
sys.stdout.write('\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment