## Parsing the Input

The input this time is a file consisting of ‘#’ and ‘.’ and we only need a list of each line. We can accomplish this by using the file.readlines() function.

1 2 3 4 5 6 7 8 9 10 11 |
..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.# |

1 2 |
with open('filename', 'r') as f: data = f.readlines() |

## Part 1

The file above is a map of the terrain, which repeats indefinitely horizontally. The goal is to count the amount of trees you bump into when given a slope to travel down the slope we are given is right 3, down 1. We start at the top left of the map of the toboggan track where ‘#’ indicates a tree and ‘.’ indicates an open square. we can find the width of the track by getting the length of a line of the data, then we set x to how far right we are travelling and y to how far down.

We initialise a trees variable which starts at 0 and then initalise a while loop which goes until we get to the bottom of the track. under the while loop we want to increment the trees variable if we are on a tree, then we increment our y and x variables by how far we travel. When we increment x, we need to make sure we do not get an index error, so once we increment it, we have to change x to x mod width.

After counting all the trees, we return the amout we counted.

1 2 3 4 5 6 7 8 9 10 11 |
def count_trees(right=3, down=1): width = len(data[0]) x = right % width y = down trees = 0 while y < len(data): if data[y][x] == '#': trees += 1 x = (x + right) % width y += down return trees |

## Part 2

Part 2 asks us to find the amount of trees we bump into for different slopes. This is good because we can reuse the function we wrote for the first part. It gives us slopes and asks us to multiply the outcomes, so all we need to do is iter through the slopes, plug them into the function and multiply the results.

1 2 3 4 5 |
def part_2(): trees = 1 for right, down in ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2)): trees *= count_trees(right, down) return trees |