DEV Community

Viper
Viper

Posted on • Updated on

Advent of Code 2021 Python Solution: Day 2

Again, I will be using my helper function created on day 1 and the input data will be in same format.

Part 1

hs = 0
vs = 0

for d in data:
    k,v = d.split()

    if k =="forward":
        hs+=int(v)
    elif k == "down":
        vs+=int(v)
    elif k=="up":
        vs-=int(v)

print(hs*vs)
Enter fullscreen mode Exit fullscreen mode

Answer of test data will be 150 and of real input will be 1947824, we just have to give data1 instead of data in loop.

Part 2

hs = 0
vs = 0
aim = 0

for d in data1:
    k,v = d.split()
    v = int(v)

    if k =="forward":
        hs+=v
        vs+=aim*v
    elif k == "down":
        aim+=v
#         vs+=v
    elif k=="up":
        aim-=v
#         vs-=v

print(hs*vs)
Enter fullscreen mode Exit fullscreen mode

The output of above code will be 1813062561.

All of my codes are available in GitHub as Jupyter Notebook.

Why not read more?

Top comments (0)