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.

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:
        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()))
Avatar for Tanishq Chaudhary

Producing high-quality intuitive explanations of interview problems. Currently covering LeetCode and InterviewBit.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

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