with open('puzzle.txt', 'r') as f: lines = f.read().splitlines() xmas = 0 for y in range(len(lines)): for x in range(len(lines[y])): if lines[y][x] == 'X': if lines[y][x:x + 4] == 'XMAS': xmas += 1 if lines[y][x - 3:x + 1] == 'SAMX': xmas += 1 extra_check = [] if y > 2: extra_check.append(f'X{lines[y - 1][x]}{lines[y - 2][x]}{lines[y - 3][x]}') if x > 2: extra_check.append(f'X{lines[y - 1][x - 1]}{lines[y - 2][x - 2]}{lines[y - 3][x - 3]}') if y > 2 and x < len(lines[y]) - 3: extra_check.append(f'X{lines[y - 1][x + 1]}{lines[y - 2][x + 2]}{lines[y - 3][x + 3]}') if y < len(lines) - 3: extra_check.append(f'X{lines[y + 1][x]}{lines[y + 2][x]}{lines[y + 3][x]}') if x > 2: extra_check.append(f'X{lines[y + 1][x - 1]}{lines[y + 2][x - 2]}{lines[y + 3][x - 3]}') if y < len(lines) - 3 and x < len(lines[y]) - 3: extra_check.append(f'X{lines[y + 1][x + 1]}{lines[y + 2][x + 2]}{lines[y + 3][x + 3]}') for check in extra_check: if check == 'XMAS': xmas += 1 print(xmas)