#Skip to menu

Day 6, Year 2015: Probably a Fire Hazard

First read the problem description.
import numpy as np

def new_grid(h, w):
    return np.zeros((h, w), dtype=np.int64)
    
def turn_on(g, f, t, min=0, max=1):
    g[f[0]:t[0]+1, f[1]:t[1]+1] += 1
    np.clip(g, min, max, out=g)
    
def turn_off(g, f, t, min=0, max=1):
    g[f[0]:t[0]+1, f[1]:t[1]+1] -= 1
    np.clip(g, min, max, out=g)
    
def toggle(g, f, t, min=0, max=1):
    if min == 0 and max == 1:
        g[f[0]:t[0]+1, f[1]:t[1]+1] = (g[f[0]:t[0]+1, f[1]:t[1]+1] + 1) % 2
    else:
        g[f[0]:t[0]+1, f[1]:t[1]+1] += 2
    
    np.clip(g, min, max, out=g)
    
def action(s):
    a = None
    if s.startswith('turn on'):
        s = s[len('turn on '):]
        a = 1
    elif s.startswith('turn off'):
        s = s[len('turn off '):]
        a = 2
    elif s.startswith('toggle'):
        s = s[len('toggle '):]
        a = 3
    else:
        return None
    
    fields = s.split(' ')
    f = fields[0].split(',')
    t = fields[2].split(',')
    
    f[0] = int(f[0])
    f[1] = int(f[1])
    t[0] = int(t[0])
    t[1] = int(t[1])

    return (f, t, a)

def apply_action(g, a, min=0, max=1):
    if a[2] == 1:
        turn_on(g, a[0], a[1], min, max)
    elif a[2] == 2:
        turn_off(g, a[0], a[1], min, max)
    elif a[2] == 3:
        toggle(g, a[0], a[1], min, max)
    else:
        return
g = new_grid(1000, 1000)
turn_on(g, (0,0), (999,999))
assert np.sum(g) == 1000*1000
toggle(g, (0,0), (999,0))
assert np.sum(g) == 1000*1000 - 1000
turn_off(g, (499,499), (500,500))
assert np.sum(g) == 1000*1000 - 1000 - 4
import import_ipynb
import helper
s = helper.read_file('2015_6.txt')
g = new_grid(1000, 1000)
for l in s.splitlines():
    apply_action(g, action(l))
np.sum(g)
569999
g = new_grid(1000, 1000)
for l in s.splitlines():
    apply_action(g, action(l), min=0, max=None)
np.sum(g)
17836115

Source code of the solution(s):