import re with open("05.txt") as f: data = f.read() def solve(data, part2=False): crates, insns = data.split("\n\n") crates = crates.split("\n") insns = insns.split("\n") stacks = dict() crateDefs, stackNames = crates[:-1], crates[-1] # Parse crateCoords: dict[int, list[str]] = dict() for i, line in enumerate(crateDefs): for j, c in enumerate(line): if c == "[": j2 = j // 4 bucket = j2 if bucket not in crateCoords: crateCoords[bucket] = [] crateCoords[bucket].insert(0, line[j + 1]) pat = re.compile(r"move (\d+) from (\d+) to (\d+)") for line in insns: m = pat.match(line) if m is None: continue c, f, t = int(m.group(1)), int(m.group(2)) - 1, int(m.group(3)) - 1 moved = crateCoords[f][-c:] crateCoords[f] = crateCoords[f][:-c] crateCoords[t] += (moved if part2 else moved[::-1]) for i in sorted(crateCoords.keys()): stk = crateCoords[i] print(stk[-1], end="") print() ex_data = """ [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2""" solve(ex_data) solve(data) solve(ex_data, part2=True) solve(data, part2=True)