#!/usr/bin/env python3 import re import numpy as np lines = (x.strip() for x in open("input.txt")) REGEX_RANGES = re.compile(r"^([a-z ]+): (\d+)-(\d+) or (\d+)-(\d+)$") REGEX_TICKET = re.compile(r"^(\d+,)*\d+$") read_step = 0 mtype = '|S30,i4,i4,i4,i4' names = np.array([], dtype=str) groups = [] tickets = [] for line in lines: match = REGEX_RANGES.match(line) if match: m_groups = match.groups() names = np.append(names, [m_groups[0]]) groups.append(list(map(int, m_groups[1:]))) match = REGEX_TICKET.match(line) if match: ticket = tuple(map(int, line.split(','))) tickets.append(ticket) groups = np.array(groups) tickets = np.array(tickets, dtype=np.int32) ranges = np.concatenate((groups[:, :2], groups[:, 2:]), axis=0) valids = np.full(tickets.shape, False) for idx, elem in np.ndenumerate(tickets): valids[idx] = np.any(np.logical_and(ranges[:, 0] <= elem, elem <= ranges[:, 1])) print(np.ma.array(tickets, mask=valids).sum())