#!/usr/bin/python3 import fileinput import re stack = [] stack.append([]) # for convenience, element 0, not used def setup(line): i = 1 num = 1 while i < len(line): if line[i] != ' ': while num >= len(stack): stack.append([]) stack[num].append(line[i]) i += 4 num += 1 def move(line): r = r'move (\d+) from (\d+) to (\d+)' result = re.search(r, line) num, fro, to = list(map(int, result.groups())) # print("num = %d, fro = %d, to = %d" % (num, fro, to)) grab = stack[fro][0:num] ## grab = grab[::-1] stack[fro] = stack[fro][num:] stack[to] = grab + stack[to] # Get initial state. state = 0 for line in fileinput.input(): line = line.rstrip() if line == "": state = 1 continue if line.startswith(' 1'): continue if state == 0: setup(line) else: move(line) # print(stack) tops = "" for i in range(1, len(stack)): tops += stack[i][0] print(tops)