serial = 5535 cache = dict() def get_power_level(x, y): if (x, y) in cache: return cache.get((x, y)) rack_id = x + 10 power_level = rack_id * y power_level += serial power_level *= rack_id power_level = (power_level // 100) % 10 power_level -= 5 cache[(x, y)] = power_level return power_level m = dict() for size in range(1, 301): # for size in range(1, 4): print('checking size:', size) for x in range(0, 301 - size): for y in range(0, 301 - size): level = m.get((x, y, size - 1)) or 0 j = size - 1 for i in range(0, size - 1): level += get_power_level(x + i, y + j) level += get_power_level(x + j, y + i) level += get_power_level(x + size - 1, y + size - 1) m[(x, y, size)] = level pos = max(m, key=m.get) print(f'{pos[0]},{pos[1]},{pos[2]}')