DEV Community

loading...

Advent of Code 2020: Day 1 Python Solution

iamdurga profile image Durga Pokharel Updated on ・2 min read

While learning python, I was searching for learning more complex problems to get adventure of exercise and then I found the AdventOfCode. Although the challenge has already been completed, I heard from a friend that this challenge will take our way of solving problems to higher.

Each day has 2 problems to solve and each part has a story too.

Part 1

Finding the product of 2 numbers in a file that sums to 2020. I started by writing small block of code. And testing my code with the given example data and if it works fine then I test it with my input.

Prepare data directory.

data_dir = "Data/"
Enter fullscreen mode Exit fullscreen mode

Import regular expression to find digits and place them on a list.

import re
day1 = open(data_dir+"day1_test.txt").read()
nums = [int(i) for i in re.findall(r"[0-9]+", day1)]
Enter fullscreen mode Exit fullscreen mode

Find two numbers which sums up to 2020. I am lucky that there are only 2 numbers.

sol = []
for num in nums:
    if 2020-num in nums:
        sol.append((2020-num, num))
sol = sol[0]
print(f"Two numbers that sum to 2020 are {sol[0]} and {sol[1]}. Their product is {sol[0]*sol[1]}")
Enter fullscreen mode Exit fullscreen mode

A function for part1

def solve_day1_part1(filename="day1_test.txt", data_dir = "Data/"):
    day1 = open(data_dir+filename).read()
    nums = [int(i) for i in re.findall(r"[0-9]+", day1)]

    sol = []
    for num in nums:
        if 2020-num in nums:
            sol.append((2020-num, num))
    sol = sol[0]
    print(f"Two numbers that sum to 2020 are {sol[0]} and {sol[1]}. Their product is {sol[0]*sol[1]}")
solve_day1_part1(filename="day1.txt")
Enter fullscreen mode Exit fullscreen mode

Function for part2

def solve_day1_part2(filename="day1_test.txt", data_dir = "Data/"):
    day1 = open(data_dir+filename).read()
    nums = [int(i) for i in re.findall(r"[0-9]+", day1)]

    sol = []
    for num1 in nums[:-2]:
        for num2 in nums[1:]:
            if 2020-num1-num2 in nums:
                sol.append([num1, num2, 2020-num1-num2])
    print(sol)
    sol=sol[0]
    print(f"Three numbers that sum to 2020 are {sol[0]}, {sol[1]} and {sol[2]}. Their product is {sol[0]*sol[1]*sol[2]}")
solve_day1_part2(filename="day1_test.txt")

Enter fullscreen mode Exit fullscreen mode

I am updating my GitHub Repository after each solution I tried.

Discussion (0)

Forem Open with the Forem app