#Skip to menu

Day 2, Year 2021: Dive!

First read the problem description.
class Submarine():
    horizontal = 0
    depth = 0
    aim = 0

    use_aim = False

    def __init__(self, use_aim=False):
        self.use_aim = use_aim

    def down(self, n):
        if self.use_aim:
            self.aim += n
        else:
            self.depth += n
            
    def up(self, n):
        if self.use_aim:
            self.aim -= n
        else:
            self.depth -= n

    def forward(self, n):
        self.horizontal += n
        
        if self.use_aim:
            self.depth += n * self.aim

import import_ipynb
import helper
f = helper.open_file('2021_2.txt')

s = Submarine()
sa = Submarine(use_aim=True)

for l in f:
    d, n = l.split(' ')
    f = None
    if d == 'forward':
        f = Submarine.forward
    elif d == 'up':
        f = Submarine.up
    elif d == 'down':
        f = Submarine.down

    f(s, int(n))
    f(sa, int(n))
    

print(s.horizontal * s.depth)
print(sa.horizontal * sa.depth)
1694130
1698850445

Source code of the solution(s):