05_stacks.py 750 B

1234567891011121314151617181920
  1. #!/usr/bin/env python3
  2. import sys
  3. from itertools import islice, takewhile
  4. def parse(f):
  5. rows = (l[1::4] for l in takewhile(lambda l: not l.startswith(' 1'), f))
  6. yield [[ord(c) for c in reversed(col) if c != ' '] for col in zip(*rows)]
  7. yield [(int(num), int(src) - 1, int(dst) - 1)
  8. for (_, num, _, src, _, dst) in map(str.split, islice(f, 1, None))]
  9. def move(stacks, moves, multipop):
  10. for num, src, dst in moves:
  11. popped = stacks[src][-num:]
  12. del stacks[src][-num:]
  13. stacks[dst].extend(popped if multipop else reversed(popped))
  14. return ''.join(chr(stack[-1]) for stack in stacks)
  15. stacks, moves = parse(sys.stdin)
  16. print(move(list(map(list, stacks)), moves, False))
  17. print(move(stacks, moves, True))