The first day of the new years challenges came with a nice relaxing solution.
Parsing the Input
The input is given as a list of integers seperated by line breaks like the following.
1 2 3 4 5 6 |
1721 979 366 299 675 1456 |
This can be parsed in python by reading the file, and creating a set containing the integer of each line. The reason a set is preferred as opposed to a list is because in this problem, there are no repeated numbers and for lookups, sets have on average an O(1) time complexity whereas lists have O(n) time complexity.
1 2 |
with open('filename', 'r') as f: nums = set(int(x) for x in f) |
Part 1
In part 1, we have to find the only 2 integers in that set that add to 2020 and then multiply them together. this can be accomplished by iterating through the set and seeing if the number that would make the sum total 2020 existed in the set. When found, the product of the 2 numbers is returned.
1 2 3 4 5 |
def part_1(): for i in nums: j = 2020 - i if j in nums: return i * j |
Part 2
Part 2 is similar to part 1, but we have to find 3 numbers in the set that add to 2020. This can be done in primarily the same way, but we need to iter through the set a second time so we can know if the third number that sums to 2020 is in the set. Once again when we have found the 3 numbers, we multiply them together and return the result.
1 2 3 4 5 6 |
def part_2(): for i in nums: for j in nums: k = 2020 - i - j if k in nums: return i * j * k |