import fileinput from pprint import pprint from copy import deepcopy layout = [] for line in fileinput.input(): if line.strip(): layout.append(list(line.strip())) part1 = -1 old_layout = deepcopy(layout) row_length = len(old_layout[0]) while True: new_layout = [[None] * len(row) for row in old_layout] for y in range(len(old_layout)): for x in range(len(old_layout[0])): if old_layout[y][x] == ".": new_layout[y][x] = old_layout[y][x] continue count = sum( ( x >= 1 and old_layout[y][x - 1] == "#", x < row_length - 1 and old_layout[y][x + 1] == "#", ) ) if y >= 1: count += sum( ( x >= 1 and old_layout[y - 1][x - 1] == "#", old_layout[y - 1][x] == "#", x < row_length - 1 and old_layout[y - 1][x + 1] == "#", ) ) if y < len(layout) - 1: count += sum( ( x >= 1 and old_layout[y + 1][x - 1] == "#", old_layout[y + 1][x] == "#", x < row_length - 1 and old_layout[y + 1][x + 1] == "#", ) ) if count == 0: new_layout[y][x] = "#" elif count >= 4: new_layout[y][x] = "L" else: new_layout[y][x] = old_layout[y][x] new_part1 = sum(sum(s == "#" for s in row) for row in new_layout) if part1 == new_part1: break part1 = new_part1 old_layout = new_layout print(part1) part2 = -1 old_layout = deepcopy(layout) def get(x, y, dx, dy): try: x += dx y += dy while old_layout[y][x] == ".": if x < 0 or y < 0: raise IndexError x += dx y += dy except: return "." return old_layout[y][x] while True: new_layout = [[None] * len(row) for row in old_layout] for y in range(1, len(old_layout) - 1): for x in range(1, len(old_layout[0]) - 1): if old_layout[y][x] == ".": new_layout[y][x] = old_layout[y][x] continue count = sum( ( get(x, y, -1, -1) == "#", get(x, y, -1, 0) == "#", get(x, y, -1, 1) == "#", get(x, y, 0, -1) == "#", get(x, y, 0, 1) == "#", get(x, y, 1, -1) == "#", get(x, y, 1, 0) == "#", get(x, y, 1, 1) == "#", ) ) if count == 0: new_layout[y][x] = "#" elif count >= 5: new_layout[y][x] = "L" else: new_layout[y][x] = old_layout[y][x] new_part2 = sum(sum(s == "#" for s in row) for row in new_layout) if part2 == new_part2: break part2 = new_part2 old_layout = new_layout print(part2)