[py] Simplify 2022_05

This commit is contained in:
Joscha 2022-12-05 22:21:41 +01:00
parent 0e1afe2017
commit bcfe9de9af

View file

@ -1,32 +1,24 @@
def solve(inputstr): def solve(inputstr):
stackstr, movestr = inputstr.split("\n\n") stackstr, movestr = inputstr.split("\n\n")
stacks = [] stacklines = stackstr.splitlines()[:-1]
for line in stackstr.splitlines()[:-1]: stacks = [[] for _ in range((len(stacklines[-1]) + 1) // 4)]
i = 0 for line in stacklines[::-1]:
while line: for i, c in enumerate(line[1::4]):
crate, line = line[:3], line[4:] if c != " ":
if len(stacks) <= i: stacks[i].append(c)
stacks.append([])
if crate[0] == "[":
stacks[i].append(crate[1])
i += 1
for stack in stacks:
stack.reverse()
moves = [] moves = []
for line in movestr.splitlines(): for line in movestr.splitlines():
_, amount, _, source, _, target = line.split() _, amount, _, source, _, target = line.split()
moves.append((int(amount), int(source), int(target))) moves.append((int(amount), int(source), int(target)))
# Part 1
part1 = [list(stack) for stack in stacks] part1 = [list(stack) for stack in stacks]
for amount, source, target in moves: for amount, source, target in moves:
for _ in range(amount): part1[target - 1].extend(part1[source - 1][-amount:][::-1])
part1[target - 1].append(part1[source - 1].pop()) part1[source - 1] = part1[source - 1][:-amount]
print("Part 1:", "".join(stack[-1] for stack in part1)) print("Part 1:", "".join(stack[-1] for stack in part1))
# Part 2
part2 = [list(stack) for stack in stacks] part2 = [list(stack) for stack in stacks]
for amount, source, target in moves: for amount, source, target in moves:
part2[target - 1].extend(part2[source - 1][-amount:]) part2[target - 1].extend(part2[source - 1][-amount:])