#!/usr/bin/python3 import re with open("input") as fh: state = "rules" rules = {} nearby = [] for ln in fh: ln = ln.strip() if state == "rules": if m := re.match(r"([a-z ]+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)", ln): rules[m.group(1)] = ((int(m.group(2)), int(m.group(3))), (int(m.group(4)), int(m.group(5)))) elif ln == "your ticket:": state = "your" elif ln == "": pass else: raise RuntimeError(ln) elif state == "your": if re.match(r"[0-9,]+", ln): my_ticket = ln.split(",") elif ln == "nearby tickets:": state = "nearby" elif ln == "": pass else: raise RuntimeError(ln) elif state == "nearby": if re.match(r"[0-9,]+", ln): ticket = [int(x) for x in ln.split(",")] nearby.append(ticket) elif ln == "": pass else: raise RuntimeError(ln) ticket_scanning_error_rate = 0 for ticket in nearby: for num in ticket: ok = False for rule in rules.values(): if rule[0][0] <= num <= rule[0][1] or rule[1][0] <= num <= rule[1][1]: ok = True break if not ok: ticket_scanning_error_rate += num print(ticket_scanning_error_rate)