from pprint import pprint with open("data.txt", "r", encoding="utf-8") as f: data = [x.rstrip() for x in f] def traverse(tx, ty): x = y = 0 max_x = len(data[0]) max_y = len(data) - 1 trees = 0 while True: x += tx xi = x % max_x y += ty if y > max_y: return trees assert data[y][xi] in (".", "#") if data[y][xi] == "#": trees += 1 trees = 1 for x in ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2)): z = traverse(*x) print(f"The toboggan encountered {z} trees.") trees *= z print(f"Sum: {trees}")