|
| 1 | +from typing import Any, Union |
| 2 | + |
| 3 | + |
| 4 | +def read_input(filepath): |
| 5 | + |
| 6 | + with open(filepath) as f: |
| 7 | + return list(map(int, f.readlines())) |
| 8 | + |
| 9 | +def sum_to_target(transactions, target=2020): |
| 10 | + |
| 11 | + transactions = set(transactions) |
| 12 | + # also makes a set {1,2,3}, but {} is an empty dictionary |
| 13 | + for bill in transactions: |
| 14 | + # sorry dave! |
| 15 | + if (target - bill) in transactions: |
| 16 | + return tuple(sorted((bill, (target - bill)))) |
| 17 | + # defining a tuple |
| 18 | + |
| 19 | +def find_target(transactions, target=2020): |
| 20 | + for number in transactions: |
| 21 | + new_target = target - number |
| 22 | + other_numbers = sum_to_target(transactions, new_target) |
| 23 | + if other_numbers is not None: |
| 24 | + return tuple(sorted((number, *other_numbers))) |
| 25 | + # * unpacks the tuple output by sum_to_target |
| 26 | + # |
| 27 | + |
| 28 | +def main(): |
| 29 | + |
| 30 | + transactions = read_input('../input.txt') |
| 31 | + # print(transactions) |
| 32 | + |
| 33 | + num1, num2 = sum_to_target(transactions) |
| 34 | + |
| 35 | + part1_answer = num1 * num2 |
| 36 | + |
| 37 | + print(part1_answer) |
| 38 | + |
| 39 | + num1, num2, num3 = find_target(transactions, target=2020) |
| 40 | + |
| 41 | + part2_answer = num1 * num2 * num3 |
| 42 | + |
| 43 | + print(part2_answer) |
| 44 | + |
| 45 | + |
| 46 | +if __name__ == '__main__': |
| 47 | + main() |
| 48 | + |
0 commit comments