Advent of Code 2021 | Day 1 | Solution in Python3

These are the solutions for both the parts in the Advent of Code 2021 Day 1.

Part 1 Solution

from math import inf


def get_input():
    data = []
    with open("input.txt") as f:
        data = f.readlines()
    return [int(line) for line in data]


def solve(depths):
    prev = inf
    count = 0
    for depth in depths:
        if depth > prev:
            count += 1
        prev = depth
    return count


print(solve(get_input()))

Part 2 Solution

from math import inf


def get_input():
    data = []
    with open("input.txt") as f:
        data = f.readlines()
    return [int(line) for line in data]


def solve(depths):
    prev = inf
    count = 0
    n = len(depths)
    for i in range(2, n):
        window = sum(depths[i - 2 : i + 1])
        if window > prev:
            count += 1
        prev = window
    return count


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.