Dusty Shed
Tally how often each ID appears, then sort by the tally.
The puzzle
The input is a long list of container ID numbers, one per line, and many IDs repeat. Part 1 asks for the three IDs that appear most often, multiplied together.
Part 2 asks for the same thing at the other end: the three IDs that appear least often, multiplied together.
For a small example, take this list of 11 IDs:
12
7
30
12
9
7
12
41
30
7
12
12 appears four times, 7 three times, 30 twice, and 9 and 41 once each. The three most common are 12, 7 and 30, so part 1’s answer is 12 × 7 × 30 = 2520. The three least common are 9, 41 and 30, so part 2’s answer is 9 × 41 × 30 = 11070.
How I solved it
In part1 I count every line in a dictionary keyed by the raw line, using ids.get(ln, 0) + 1 so a new ID starts at zero. Then I sort the dictionary’s items by count, highest first, take the first three, turn their keys back into integers, and multiply them with math.prod.
sort = list(sorted(ids.items(), key=lambda item: item[1], reverse=True))
counts = [int(x[0]) for x in sort[:3]]
return math.prod(counts)
part2 is a copy of part1 with the sort flipped to reverse=False, so the rarest IDs come first. That was the only change, and the second star came 44 seconds after the first.
The code
import argparse
import re, math
class Solution:
filename_real_input = 'real_input.txt'
filename_test_input = 'test_input.txt'
@staticmethod
def get_nums(string: str) -> list[int]:
return list(map(int, re.findall(r'[-+]?\d+', string)))
def __init__(self, test=False):
self.filename = self.filename_test_input if test else self.filename_real_input
self.file = open(self.filename,'r').read()
self.lines = self.file.splitlines()
def part1(self):
ids = {}
for ln in self.lines:
cur = ids.get(ln, 0)
ids[ln] = cur + 1
sort = list(sorted(ids.items(), key=lambda item: item[1], reverse=True))
counts = [int(x[0]) for x in sort[:3]]
return math.prod(counts)
pass
def part2(self):
ids = {}
for ln in self.lines:
cur = ids.get(ln, 0)
ids[ln] = cur + 1
sort = list(sorted(ids.items(), key=lambda item: item[1], reverse=False))
counts = [int(x[0]) for x in sort[:3]]
return math.prod(counts)
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser('Solution file')
parser.add_argument('-part', required=True, type=int, help='Part (1/2)')
parser.add_argument('-test', required=True, type=str, help='Test mode (True/False)')
args = parser.parse_args()
test = True if args.test in ['True','true'] else False
solution = Solution(test=test)
result = solution.part1() if args.part == 1 else solution.part2()
print(result)problems/2026/day_1/solution.py on GitHub ↗