From 03abb1a5ae384dd8ae4ffa17f03941ceef2cf995 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Tue, 1 Dec 2020 16:50:45 +0100 Subject: [PATCH] day1: modify python for part2 --- 2020/day1/day1.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/2020/day1/day1.py b/2020/day1/day1.py index 8371aee..b7a8f39 100755 --- a/2020/day1/day1.py +++ b/2020/day1/day1.py @@ -1,15 +1,22 @@ #!/usr/bin/env python +import itertools import sys from typing import Iterable -def find2020(nums: Iterable[int]) -> int: - candidates = set() +def product(nums: Iterable[int]) -> int: + """ + Returns the product of all elements in 'nums' + """ + x = 1 for num in nums: - opposite = 2020-num - if num in candidates: - return num * opposite - candidates.add(opposite) + x *= num + return x + +def find_summing(arity: int, nums: Iterable[int]) -> int: + return product(next(filter(lambda xs: sum(xs) == 2020, itertools.permutations(nums, r=arity)))) if __name__ == '__main__': with open(sys.argv[1], 'r') as f: - print(find2020(int(n) for n in f.readlines())) + nums = [int(n) for n in f.readlines()] + print(find_summing(2, nums)) + print(find_summing(3, nums))