05_stacks.py 897 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/env python3
  2. import sys
  3. def parse(f):
  4. stacks = [[] for i in range(9)]
  5. moves = []
  6. for line in f:
  7. if line.startswith(' 1 '):
  8. break
  9. for i, crate in enumerate(line[1::4]):
  10. if crate != ' ':
  11. stacks[i].append(ord(crate))
  12. for stack in stacks:
  13. stack.reverse()
  14. next(f)
  15. for line in f:
  16. num, src, dst = map(int, line.split()[1::2])
  17. moves.append((num, src - 1, dst - 1))
  18. return stacks, moves
  19. def move(stacks, moves, multipop):
  20. for num, src, dst in moves:
  21. popped = stacks[src][-num:]
  22. del stacks[src][-num:]
  23. if not multipop:
  24. popped.reverse()
  25. stacks[dst].extend(popped)
  26. return ''.join(chr(stack[-1]) for stack in stacks)
  27. stacks, moves = parse(sys.stdin)
  28. print(move(list(map(list, stacks)), moves, False))
  29. print(move(stacks, moves, True))