-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadvent-01.py
60 lines (46 loc) · 1.57 KB
/
advent-01.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
URL for challenge: https://adventofcode.com/2020/day/1
"""
from functools import reduce
from operator import mul
def process_input():
f = open("advent-01-input.txt")
return [int(line) for line in f.readlines()]
def part1(target_amount, amounts):
"""
By taking the intersection of the set of given amounts
with the set of their inverses, the only amounts
that will be left will be x and (target - x).
"""
pair_entries = {target_amount - x for x in amounts}.intersection(amounts)
num_entries = len(pair_entries)
if num_entries == 1:
return pair_entries.pop() ** 2
if num_entries == 2:
return reduce(mul, pair_entries)
# This case is only possible when Part 1 is used by Part 2
return None
def part2():
amounts = process_input()
inverse_amounts = [2020 - x for x in amounts]
"""
Suppose x + inv = 2020 and x is assumed to be part of
the solution, check if it is possible to find two
numbers y, z from amounts-[x] s.t. y + z = inv
(i.e. check existence of solution for part 1 with
inputs inv and amounts-[x]).
"""
for idx, inv in enumerate(inverse_amounts):
sub_solution = part1(inv, amounts[:idx] + amounts[idx+1:])
if sub_solution is not None:
return amounts[idx] * sub_solution
def run():
chall = int(input("Please enter either 1 or 2 for the challenges: "))
if chall == 1:
print(part1(2020, process_input()))
elif chall == 2:
print(part2())
else:
print("You need to enter either 1 or 2")
exit(1)
run()