Advent of Code 2021 | Day 2 | Solutions in Python3
These are the solutions to today’s aka day 2’s Advent of Code 2021 in Python3. They are pretty self explanatory. Problem Link.
Contents hide
Problem Setup
- input: a list of
commands
in the formatcommand value
- where each
command
is one offorward
orup
ordown
- output: multiple
horizontal distance
anddepth
Part 1 Solution
Given how the forward, up and down change we get something as shown below:
def get_input(): data = [] with open("input.txt") as f: data = f.readlines() return data def solve(commands): horizontal = 0 depth = 0 for full_command in commands: command, value = full_command.split() value = int(value) if command == "forward": horizontal += value elif command == "up": depth -= value elif command == "down": depth += value return horizontal * depth print(solve(get_input()))
Part 2 Solution
Given how the forward, up and down change we get something as shown below:
from collections import defaultdict def get_input(): data = [] with open("input.txt") as f: data = f.readlines() return data def solve(commands): horizontal = 0 depth = 0 aim = 0 for full_command in commands: command, value = full_command.split() value = int(value) if command == "forward": horizontal += value depth += aim * value elif command == "up": aim -= value elif command == "down": aim += value return horizontal * depth print(solve(get_input()))
Recommended Posts
Advent of Code 2021 | Day 6 | Solutions in Python3
December 6, 2021
Advent of Code 2021 | Day 5 | Solutions in Python3
December 5, 2021
Advent of Code 2021 | Day 4 | Solution Explained in Python3
December 4, 2021