···11import fileinput
223344+SIZE = 300
55+66+47def power_level(x, y, serial):
55- x += 1
66- y += 1
78 rack_id = x + 10
89 return (((rack_id * y + serial) * rack_id // 100) % 10) - 5
91010111111-SERIAL = int(fileinput.input()[0])
1212-SIZE = 300
1313-GRID = [[power_level(x, y, SERIAL) for x in range(SIZE)] for y in range(SIZE)]
1212+def power_search(partials, conv_size):
1313+ best_power = 0
1414+ best_x = 0
1515+ best_y = 0
14161515-overall_sum = 0
1616-overall_x = 0
1717-overall_y = 0
1818-overall_size = 0
1717+ for y in range(1, SIZE - conv_size + 1):
1818+ for x in range(1, SIZE - conv_size + 1):
1919+ xx = x + conv_size
2020+ yy = y + conv_size
2121+ power = PARTIALS[yy][xx] + PARTIALS[y][x] - PARTIALS[y][xx] - PARTIALS[yy][x]
19222020-for size in range(3, 16): # window size of 16 is good enough...right?
2121- best_sum = 0
2222- best_x = 0
2323- best_y = 0
2323+ if power > best_power:
2424+ best_power = power
2525+ best_x = x + 1
2626+ best_y = y + 1
24272525- for y in range(SIZE - size):
2626- for x in range(SIZE - size):
2727- total = 0
2828- for j in range(size):
2929- for i in range(size):
3030- total += GRID[y + j][x + i]
2828+ return best_power, best_x, best_y, conv_size,
31293232- if total > best_sum:
3333- best_sum = total
3434- best_x = x
3535- best_y = y
36303737- if size == 3:
3838- print "Coordinate of most powerful 3x3 grid: {},{}".format(best_x + 1, best_y + 1)
3131+SERIAL = int(fileinput.input()[0])
3232+PARTIALS = [[0 for _ in range(SIZE + 1)] for _ in range(SIZE + 1)]
39334040- if best_sum > overall_sum:
4141- overall_sum = best_sum
4242- overall_x = best_x
4343- overall_y = best_y
4444- overall_size = size
3434+for y in range(1, SIZE + 1):
3535+ for x in range(1, SIZE + 1):
3636+ PARTIALS[y][x] = power_level(x, y, SERIAL) + PARTIALS[y][x-1] + PARTIALS[y-1][x] - PARTIALS[y-1][x-1]
45374646-print "Identifier of the largest total power: {},{},{}".format(overall_x + 1, overall_y + 1, overall_size)
3838+print "Coordinate of most powerful 3x3 grid: {1},{2}".format(*power_search(PARTIALS, 3))
3939+print "Identifier of the largest total power: {1},{2},{3}".format(*max(power_search(PARTIALS, n) for n in range(1, SIZE)))