From 4a8c905fd24d7774fb6f40eeff00cf16cbe0d6be Mon Sep 17 00:00:00 2001 From: Edoardo Baldi Date: Thu, 19 Dec 2024 20:48:42 +0100 Subject: [PATCH] Day 19: Python (p2) --- 19/python/solution.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/19/python/solution.py b/19/python/solution.py index 4ab48e4..c0fa409 100644 --- a/19/python/solution.py +++ b/19/python/solution.py @@ -36,14 +36,11 @@ def insert(self, *patterns: str) -> None: node = node.children[char] node.is_end = True - def search(self, string: str, debug: bool = False) -> bool: + def _dp_search(self, string: str, count: bool = False) -> bool | int: n = len(string) - dp = [True] + [False] * n + dp = [1] + [0] * n for i in range(n): - if debug: - print(dp) - if not dp[i]: continue @@ -53,11 +50,16 @@ def search(self, string: str, debug: bool = False) -> bool: node = node.children[string[j]] j += 1 if node.is_end: - dp[j] = True - if j == n: - return True + dp[j] = dp[j] + dp[i] if count else True + return dp[n] + def search(self, string: str) -> bool: + return bool(self._dp_search(string, count=False)) + + def count(self, string: str) -> int: + return self._dp_search(string, count=True) + def parse_data(puzzle_input: str) -> tuple[list[str], list[str]]: """Parse input data""" @@ -74,7 +76,9 @@ def part1(patterns: list[str], designs: list[str]) -> int: def part2(patterns: list[str], designs: list[str]) -> int: """Solve part 2""" - return 0 + trie = Trie() + trie.insert(*patterns) + return sum(trie.count(d) for d in designs) def solve(puzzle_input: str) -> tuple[int, int]: