75 lines
1.9 KiB
Python
75 lines
1.9 KiB
Python
|
|
import fileinput
|
|
from typing import Iterable,List
|
|
|
|
class Puzzle:
|
|
stacks: List[List[str]]
|
|
instructions: List[str]
|
|
|
|
def __init__(self):
|
|
self.stacks = []
|
|
self.instructions = []
|
|
|
|
def parse(lines: Iterable[str]) -> Puzzle:
|
|
count = None
|
|
stage = 0
|
|
puzzle = Puzzle()
|
|
for line in map(lambda x: x.replace('\n',''), lines):
|
|
if count is None: # Figure out how many stacks
|
|
count = len(line)//4 + 1
|
|
for _ in range(count):
|
|
puzzle.stacks.append([])
|
|
#puzzle.stacks = [[]]*count
|
|
if stage == 0:
|
|
if '[' not in line:
|
|
stage = 1
|
|
continue
|
|
chars = [line[i*4+1:i*4+2] for i in range(count)]
|
|
for idx in range(count):
|
|
if chars[idx] != ' ':
|
|
puzzle.stacks[idx].append(chars[idx])
|
|
elif stage == 1:
|
|
stage = 2
|
|
elif stage == 2:
|
|
puzzle.instructions.append(line)
|
|
for idx in range(count):
|
|
puzzle.stacks[idx] = puzzle.stacks[idx][::-1]
|
|
return puzzle
|
|
|
|
def solve(p: Puzzle) -> str:
|
|
for ins in p.instructions:
|
|
_, cnt, _, fr, _, to = ins.split(' ')
|
|
cnt = int(cnt)
|
|
fr = int(fr)
|
|
to = int(to)
|
|
for _ in range(cnt):
|
|
p.stacks[to-1].append(p.stacks[fr-1].pop())
|
|
out = ''
|
|
for st in p.stacks:
|
|
out += st[-1]
|
|
return out
|
|
|
|
def solveb(p: Puzzle) -> str:
|
|
for ins in p.instructions:
|
|
_, cnt, _, fr, _, to = ins.split(' ')
|
|
cnt = int(cnt)
|
|
fr = int(fr)
|
|
to = int(to)
|
|
load = []
|
|
for _ in range(cnt):
|
|
load.append(p.stacks[fr-1].pop())
|
|
load = load[::-1]
|
|
p.stacks[to-1] += load
|
|
out = ''
|
|
for st in p.stacks:
|
|
out += st[-1]
|
|
return out
|
|
|
|
|
|
if __name__ == "__main__":
|
|
puzzle = parse(fileinput.input())
|
|
print(solve(puzzle))
|
|
puzzle = parse(fileinput.input())
|
|
print(solveb(puzzle))
|
|
|