From a6b88855c8299f2cf6c9999b42843757dd2aa45a Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Tue, 13 Dec 2022 07:38:13 +0100 Subject: [PATCH] day13 - eval() is evil; and json even makes it ~8 times faster?! --- day13.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/day13.py b/day13.py index b8ecf29..5ebdce4 100644 --- a/day13.py +++ b/day13.py @@ -1,4 +1,5 @@ from functools import cmp_to_key +from json import loads from tools.aoc import AOCDay from tools.tools import compare from typing import Any @@ -38,17 +39,20 @@ class Day(AOCDay): ] ] + def parse_input(self) -> list: + return [loads(x) for x in self.getInput() if x] + def part1(self) -> Any: - packets = self.getMultiLineInputAsArray(eval) + packets = self.parse_input() index_sum = 0 - for index, (left, right) in enumerate(packets): - if packet_compare(left, right) == -1: - index_sum += index + 1 + for x in range(len(packets) // 2): + if packet_compare(packets[x * 2], packets[x * 2 + 1]) == -1: + index_sum += x + 1 return index_sum def part2(self) -> Any: - packets = [eval(x) for x in self.getInput() if x] + packets = self.parse_input() packets.extend([[[2]], [[6]]]) sorted_packets = sorted(packets, key=cmp_to_key(packet_compare))