Skip to content

Instantly share code, notes, and snippets.

@kstrauser
Created December 4, 2023 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kstrauser/2c3f76ca3fc5009f67a650bffefc595d to your computer and use it in GitHub Desktop.
Save kstrauser/2c3f76ca3fc5009f67a650bffefc595d to your computer and use it in GitHub Desktop.
advent2023day4p2.py
#!/usr/bin/env python
from functools import cache
real = True
with open("real_1.txt" if real else "test_1.txt") as infile:
data = infile.read().strip()
def matches_in(card):
card_num, numbers = card.strip().split(": ")
they, me = numbers.split(" | ")
they_have = {int(_) for _ in they.split()}
i_have = {int(_) for _ in me.split()}
matches = len(they_have & i_have)
return int(card_num.split()[1]), matches
cards = {}
for card in data.splitlines():
card_num, matches = matches_in(card)
cards[card_num] = matches
@cache
def score(card_num):
matches = cards[card_num]
if not matches:
return 1
return 1 + sum(score(card_num + n + 1) for n in range(matches))
print(sum(score(card_num) for card_num in cards.keys()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment