from copy import deepcopy with open('5.in.test') as f: stacks, instructions = f.read().rstrip().split('\n\n') layers = stacks.split('\n') stacks = [list() for _ in range((len(layers[-1]) + 1) // 4)] for layer in reversed(layers[:-1]): for i in range(len(stacks)): c = layer[i * 4 + 1] if c != ' ': stacks[i].append(c) instructions = [i.split(' ') for i in instructions.split('\n')] instructions = [tuple(int(i) for i in (i[1], i[3], i[5])) for i in instructions] def part1(stacks, instructions): stacks = deepcopy(stacks) for count, src, dst in instructions: for _ in range(count): stacks[dst-1].append(stacks[src-1].pop()) return ''.join(s[-1] for s in stacks) def part2(stacks, instructions): stacks = deepcopy(stacks) for count, src, dst in instructions: tmp = list() for _ in range(count): tmp.append(stacks[src-1].pop()) for _ in range(count): stacks[dst-1].append(tmp.pop()) return ''.join(s[-1] for s in stacks) print(part1(stacks, instructions)) print(part2(stacks, instructions))