#!/usr/bin/python import re with open('04a.txt') as f: chars = ''.join(c for c in f.read() if c in ['X', 'M', 'A', 'S']) UP = r'S.{139}A.{139}M.{139}X' DOWN = r'X.{139}M.{139}A.{139}S' LEFT = r'SAMX' RIGHT = r'XMAS' UPLEFT = r'S.{140}A.{140}M.{140}X' UPRIGHT = r'S.{138}A.{138}M.{138}X' DOWNLEFT = r'X.{138}M.{138}A.{138}S' DOWNRIGHT = r'X.{140}M.{140}A.{140}S' ORED = '|'.join((UP, DOWN, LEFT, RIGHT, UPLEFT, UPRIGHT, DOWNLEFT, DOWNRIGHT)) REG = re.compile(f'(?={ORED})') def lookahead(s): return f'(?={s})' up = next(re.finditer(UP, chars)) print(up.pos) _UP = len(re.findall(UP, chars)) _DOWN = len(re.findall(DOWN, chars)) _LEFT = len(re.findall(LEFT, chars)) _RIGHT = len(re.findall(RIGHT, chars)) _UPLEFT = len(re.findall(UPLEFT, chars)) _UPRIGHT = len(re.findall(UPRIGHT, chars)) _DOWNLEFT = len(re.findall(DOWNLEFT, chars)) _DOWNRIGHT = len(re.findall(DOWNRIGHT, chars)) print(f'UP {_UP}') print(f'DOWN {_DOWN}') print(f'LEFT {_LEFT}') print(f'RIGHT {_RIGHT}') print(f'UPLEFT {_UPLEFT}') print(f'UPRIGHT {_UPRIGHT}') print(f'DOWNLEFT {_DOWNLEFT}') print(f'DOWNRIGHT {_DOWNRIGHT}') print(f'TOTAL {_UP + _DOWN + _LEFT + _RIGHT + _UPLEFT + _UPRIGHT + _DOWNLEFT + _DOWNRIGHT}') print(len(REG.findall(chars)))