Refactor code for API (#3)

Co-authored-by: Mikael CAPELLE <mikael.capelle@thalesaleniaspace.com>
Co-authored-by: Mikaël Capelle <capelle.mikael@gmail.com>
Reviewed-on: #3
This commit is contained in:
2024-12-08 13:06:41 +00:00
parent ab4e3e199c
commit ce315b8778
130 changed files with 4599 additions and 3336 deletions

View File

@@ -1,41 +1,43 @@
import copy
import sys
from typing import Any, Iterator
blocks_s, moves_s = (part.splitlines() for part in sys.stdin.read().split("\n\n"))
from ..base import BaseSolver
blocks: dict[str, list[str]] = {stack: [] for stack in blocks_s[-1].split()}
# this codes assumes that the lines are regular, i.e., 4 characters per "crate" in the
# form of '[X] ' (including the trailing space)
#
for block in blocks_s[-2::-1]:
for stack, index in zip(blocks, range(0, len(block), 4)):
crate = block[index + 1 : index + 2].strip()
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
blocks_s, moves_s = (part.splitlines() for part in input.split("\n\n"))
if crate:
blocks[stack].append(crate)
blocks: dict[str, list[str]] = {stack: [] for stack in blocks_s[-1].split()}
# part 1 - deep copy for part 2
blocks_1 = copy.deepcopy(blocks)
# this codes assumes that the lines are regular, i.e., 4 characters per "crate" in the
# form of '[X] ' (including the trailing space)
#
for block in blocks_s[-2::-1]:
for stack, index in zip(blocks, range(0, len(block), 4)):
crate = block[index + 1 : index + 2].strip()
for move in moves_s:
_, count_s, _, from_, _, to_ = move.strip().split()
if crate:
blocks[stack].append(crate)
for _i in range(int(count_s)):
blocks_1[to_].append(blocks_1[from_].pop())
# part 1 - deep copy for part 2
blocks_1 = copy.deepcopy(blocks)
# part 2
blocks_2 = copy.deepcopy(blocks)
for move in moves_s:
_, count_s, _, from_, _, to_ = move.strip().split()
for move in moves_s:
_, count_s, _, from_, _, to_ = move.strip().split()
count = int(count_s)
for _i in range(int(count_s)):
blocks_1[to_].append(blocks_1[from_].pop())
blocks_2[to_].extend(blocks_2[from_][-count:])
del blocks_2[from_][-count:]
# part 2
blocks_2 = copy.deepcopy(blocks)
answer_1 = "".join(s[-1] for s in blocks_1.values())
print(f"answer 1 is {answer_1}")
for move in moves_s:
_, count_s, _, from_, _, to_ = move.strip().split()
count = int(count_s)
answer_2 = "".join(s[-1] for s in blocks_2.values())
print(f"answer 2 is {answer_2}")
blocks_2[to_].extend(blocks_2[from_][-count:])
del blocks_2[from_][-count:]
yield "".join(s[-1] for s in blocks_1.values())
yield "".join(s[-1] for s in blocks_2.values())