import fileinput from collections import Counter from itertools import product def simulate(lines, dimensions=4): active_cells = { (x, y) + (0,) * (dimensions - 2) for y, row in enumerate(lines) for x, char in enumerate(row) if char == "#" } offsets = make_offsets(dimensions) # simulate 6 steps for _ in range(6): active_cells = step(active_cells, offsets) return len(active_cells) def make_offsets(dimensions): # if any(...) to exclude the start pos (zero offset) return [offset for offset in product((-1, 0, 1), repeat=dimensions) if any(offset)] def step(cells, offsets): neighbor_counts = Counter() for cell in cells: for offset in offsets: neighbor = tuple(x + dx for x, dx in zip(cell, offset)) neighbor_counts[neighbor] += 1 return { cell for cell, count in neighbor_counts.items() if count == 3 or (count == 2 and cell in cells) } def main(lines): print("Part 1:", simulate(lines, 3)) print("Part 2:", simulate(lines, 4)) if __name__ == "__main__": with fileinput.input() as f: lines = [x.rstrip() for x in f] main(lines)