-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday01_expense_report.py
71 lines (51 loc) · 1.87 KB
/
day01_expense_report.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
61
62
63
64
65
66
67
68
69
70
71
from functools import reduce
import itertools
def multiply_pair_that_sums_to(entries, sum_to):
pairs = itertools.combinations(entries, r=2)
for num1, num2 in pairs:
total = num1 + num2
if total == sum_to:
return num1 * num2
raise ValueError("no pairs found")
def multiply_triple_that_sums_to(entries, sum_to):
triples = itertools.combinations(entries, r=3)
for num1, num2, num3 in triples:
total = num1 + num2 + num3
if total == sum_to:
return num1 * num2 * num3
raise ValueError("no triples found")
def multiply_n_numbers_that_sum_to(entries, n, sum_to):
numbers = itertools.combinations(entries, r=n)
for nums in numbers:
if sum(nums) == sum_to:
return reduce(lambda a, b: a * b, nums)
raise ValueError("not found")
def test_multiply_pair_that_sums_to():
TEST_INPUT_PART_1 = """1721
979
366
299
675
1456""".split("\n")
entries = [int(item) for item in TEST_INPUT_PART_1]
result = multiply_pair_that_sums_to(entries, sum_to=2020)
assert result == 514_579
assert result == multiply_n_numbers_that_sum_to(entries, n=2, sum_to=2020)
def test_multiply_triple_that_sums_to():
TEST_INPUT_PART_1 = """1721
979
366
299
675
1456""".split("\n")
entries = [int(item) for item in TEST_INPUT_PART_1]
result = multiply_triple_that_sums_to(entries, sum_to=2020)
assert result == 241861950
assert result == multiply_n_numbers_that_sum_to(entries, n=3, sum_to=2020)
if __name__ == "__main__":
with open("2020/data/day01_input.txt") as f:
entries = [int(line) for line in f.readlines()]
part_one_result = multiply_n_numbers_that_sum_to(entries, n=2, sum_to=2020)
print(part_one_result)
part_two_result = multiply_n_numbers_that_sum_to(entries, n=3, sum_to=2020)
print(part_two_result)