# 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

## Problem Setup

• input: a list of `commands` in the format `command value`
• where each `command` is one of `forward` or `up` or `down`
• output: multiple `horizontal distance` and `depth`

## 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:
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:
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()))
```
##### Tanishq Chaudhary Producing high-quality intuitive explanations of interview problems. Currently covering LeetCode and InterviewBit.

### 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.