stacks = None def initStacks(s): global stacks stacks = [] for i in range(s): stacks.append([]) def reverseStacks(): global stacks newStacks = [] for stack in stacks: rstack = list(reversed(stack)) newStacks.append(rstack) stacks = newStacks def move(amount, source, dest): for i in range(amount): try: srcstack = stacks[source-1] dststack = stacks[dest-1] m = srcstack.pop() dststack.append(m) except IndexError: pass def printAnswer(): answer = "" for stack in stacks: answer += stack[-1] print(answer) with open("input.txt", "r") as f: line = "." while line != "": line = f.readline().strip() s = int((len(line)-3)/4 + 1) if stacks is None: initStacks(s) for i in range(s): char = line[1+i*4] if char != " ": stacks[i].append(char) reverseStacks() print(stacks) for line in f.readlines(): data = line.strip().split(" ") amount = int(data[1]) source = int(data[3]) dest = int(data[5]) move(amount, source, dest) print(stacks) printAnswer()