diff options
author | Thomas Voss <thomasvoss@live.com> | 2021-12-02 08:52:32 +0100 |
---|---|---|
committer | Thomas Voss <thomasvoss@live.com> | 2021-12-02 08:52:32 +0100 |
commit | 75a8595e4d11af5cb650844978c87348e0fa42fa (patch) | |
tree | cfe763523c750a4cef08483070d56b712252af37 /2015/19 | |
parent | d777f23d8f757af7ef17cf62f0184d094d63c782 (diff) |
Use python3.10 pattern matching
Diffstat (limited to '2015/19')
-rwxr-xr-x | 2015/19/puzzle-1.py | 31 |
1 files changed, 16 insertions, 15 deletions
diff --git a/2015/19/puzzle-1.py b/2015/19/puzzle-1.py index 8527ca0..b694c8b 100755 --- a/2015/19/puzzle-1.py +++ b/2015/19/puzzle-1.py @@ -2,29 +2,30 @@ import re + def main() -> None: replacements: dict[str, str] = {} with open("input", "r", encoding="utf-8") as f: for line in f.readlines(): - line = line.strip() - if line != "": - parts = line.split(" => ") - if len(parts) == 2: - while parts[0] in replacements: - parts[0] += "_" - replacements[parts[0]] = parts[1] - else: - molecule = line + match line.strip().split(" => "): + case [before, after]: + while before in replacements: + before += "_" + replacements[before] = after + case [mol]: + molecule = mol unique_molecules: set[str] = set() for pattern in replacements: - trim_pattern = pattern.replace("_", "") - for match in re.finditer(trim_pattern, molecule): - before = molecule[:match.start()] - after = molecule[match.start():].replace(trim_pattern, replacements[pattern], 1) - unique_molecules.add(before + after) - + trim_pattern = pattern.rstrip("_") + unique_molecules.update( + molecule[: match.start()] + + molecule[match.start() :].replace(trim_pattern, replacements[pattern], 1) + for match in re.finditer(trim_pattern, molecule) + ) + print(len(unique_molecules)) + if __name__ == "__main__": main() |