For this challenge, we need to find two numbers from our input that sum to 2020, and calculate their multiplication.
def mul(numbers):
x = 1
for n in numbers:
x *= n
return xdef day_1(nums, N = 2):
for numbers in itertools.combinations(nums, N):
if sum(numbers) == 2020:
return mul(numbers)day_1(read_numbers("day-1-example.txt"))514579
day_1(read_numbers("day-1.txt"))224436
Part two uses the same input but wants the product of three numbers that add up to 2020.
day_1(read_numbers("day-1.txt"), 3)303394260
Password rules
def is_valid(line):
rule, password = line.split(": ")
num, letter = rule.split(" ")
low, high = num.split("-")
low, high = int(low), int(high)
count = password.count(letter)
return count >= low and count <= highdef num_valid(path):
lines = read_lines(path)
valid_lines = map(is_valid, lines)
return sum(valid_lines)num_valid("day-2-example.txt")
num_valid("day-2.txt")2
528
def is_valid(line):
rule, pw = line.split(": ")
num, letter = rule.split(" ")
pos1, pos2 = num.split("-")
pos1, pos2 = int(pos1) - 1, int(pos2) - 1
res = int(pw[pos1] == letter)
res += int(pw[pos2] == letter)
return res == 1num_valid("day-2.txt")497