## DEV Community is a community of 639,856 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

loading...

# Advent of Code 2020: Day 1 Python Solution

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/"
``````

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)]
``````

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
print(f"Two numbers that sum to 2020 are {sol} and {sol}. Their product is {sol*sol}")
``````

### 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
print(f"Two numbers that sum to 2020 are {sol} and {sol}. Their product is {sol*sol}")
solve_day1_part1(filename="day1.txt")
``````

### 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
print(f"Three numbers that sum to 2020 are {sol}, {sol} and {sol}. Their product is {sol*sol*sol}")
solve_day1_part2(filename="day1_test.txt")

``````

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