Part 1
In this puzzle, we are given several lines with numbers. We are asked to find the minimum and maximum for each line and sum up the differences between min and max.
After converting all numbers into int, we can simply iterate over all lines and sum up the differences:
def part_1(spreadsheet):
checksum = 0
for line in spreadsheet:
checksum += max(line) - min(line)
return checksum
Part 2
In part 2, we should find the two numbers in each line where one evenly divides the other. The results for this divison should then be summed up.
We can again iterate over the lines. To test each possible pair of values in the line, we use the product from the itertools. Each pair of values is check if one divides the other and if yes sums up the result. We just have to exclude the pairs of two equal numbers.
def part_2(spreadsheet):
checksum = 0
for line in spreadsheet:
for a, b in itertools.product(line, line):
if a <= b:
continue
if a % b == 0:
checksum += a // b
break
return checksum
No comments:
Post a Comment