Advent of Code 2022 day 5
Is there a more efficient way to do this? Note that from
is a reserved word
in Python, so begin
was used instead.
with open("5.txt") as f: lines = f.read() head, instructions = lines.split("\n\n") def get_state(head): state = { x:"" for x in range(1, (len(head.split("\n")[0])+5)//4 + 1) } for line in reversed(head.split("\n")[:-1]): for col, i in enumerate(range(1, len(line), 4), 1): if line[i].isalpha(): state[col] += line[i] return state def carry_out_instruction(state, instruction): _, amount, _, begin, _, to = instruction.split(" ") amount = int(amount) begin = int(begin) to = int(to) print(state) for _ in range(amount): state[to] += state[begin][-1] state[begin] = state[begin][:-1] print(instruction) return state def carry_out_instructions(state, instructions): for line in instructions.split("\n")[:-1]: state = carry_out_instruction(state, line) return state def top(state): return "".join([packages[-1] for _, packages in state.items() if packages]) state = get_state(head) state = carry_out_instructions(state, instructions) print(top(state)) # part 2 def carry_out_instruction_2(state, instruction): _, amount, _, begin, _, to = instruction.split(" ") amount = int(amount) begin = int(begin) to = int(to) print(state) state[to] += state[begin][-amount:] state[begin] = state[begin][:-amount] print(instruction) return state def carry_out_instructions_2(state, instructions): for line in instructions.split("\n")[:-1]: state = carry_out_instruction_2(state, line) return state state2 = get_state(head) state2 = carry_out_instructions_2(state2, instructions) print(top(state2))