From b3b0cc8b36442a1c41c41d8ee2a21d6a06edb897 Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Mon, 5 Dec 2022 08:11:17 +0100 Subject: [PATCH] day05 - no extra list, better indices --- day05.py | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/day05.py b/day05.py index 760877c..c2efc95 100644 --- a/day05.py +++ b/day05.py @@ -16,23 +16,20 @@ class Day(AOCDay): ] ] - def get_stacks_and_moves(self) -> (list, list): + def get_stacks_and_moves(self) -> (dict, list): i = self.getInput() stacks = {} for l, line in enumerate(i): if not line: - ret = [] - for k in sorted(stacks.keys()): - ret.append(stacks[k]) - return ret, i[l+1:] + return stacks, i[l+1:] this_stacks = (len(line) + 1) // 4 for stack_num in range(this_stacks): crate = line[stack_num * 4 + 1] if ord(crate) > 64: - if stack_num not in stacks: - stacks[stack_num] = [] - stacks[stack_num].append(crate) + if stack_num + 1 not in stacks: + stacks[stack_num + 1] = [] + stacks[stack_num + 1].append(crate) def part1(self) -> Any: stacks, moves = self.get_stacks_and_moves() @@ -40,25 +37,19 @@ class Day(AOCDay): l = move.split(" ") count, move_from, move_to = map(int, [l[1], l[3], l[5]]) for _ in range(count): - stacks[move_to - 1].insert(0, stacks[move_from - 1].pop(0)) + stacks[move_to].insert(0, stacks[move_from].pop(0)) - string = "" - for x in stacks: - string += x.pop(0) - return string + return "".join(stacks[x].pop(0) for x in sorted(stacks)) def part2(self) -> Any: stacks, moves = self.get_stacks_and_moves() for move in moves: l = move.split(" ") count, move_from, move_to = map(int, [l[1], l[3], l[5]]) - stacks[move_to - 1] = stacks[move_from - 1][:count] + stacks[move_to - 1] - stacks[move_from - 1] = stacks[move_from - 1][count:] + stacks[move_to] = stacks[move_from][:count] + stacks[move_to] + stacks[move_from] = stacks[move_from][count:] - string = "" - for x in stacks: - string += x.pop(0) - return string + return "".join(stacks[x].pop(0) for x in sorted(stacks)) if __name__ == '__main__':