day13 - eval() is evil; and json even makes it ~8 times faster?!
This commit is contained in:
parent
166e62e40b
commit
a6b88855c8
14
day13.py
14
day13.py
@ -1,4 +1,5 @@
|
|||||||
from functools import cmp_to_key
|
from functools import cmp_to_key
|
||||||
|
from json import loads
|
||||||
from tools.aoc import AOCDay
|
from tools.aoc import AOCDay
|
||||||
from tools.tools import compare
|
from tools.tools import compare
|
||||||
from typing import Any
|
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:
|
def part1(self) -> Any:
|
||||||
packets = self.getMultiLineInputAsArray(eval)
|
packets = self.parse_input()
|
||||||
index_sum = 0
|
index_sum = 0
|
||||||
for index, (left, right) in enumerate(packets):
|
for x in range(len(packets) // 2):
|
||||||
if packet_compare(left, right) == -1:
|
if packet_compare(packets[x * 2], packets[x * 2 + 1]) == -1:
|
||||||
index_sum += index + 1
|
index_sum += x + 1
|
||||||
|
|
||||||
return index_sum
|
return index_sum
|
||||||
|
|
||||||
def part2(self) -> Any:
|
def part2(self) -> Any:
|
||||||
packets = [eval(x) for x in self.getInput() if x]
|
packets = self.parse_input()
|
||||||
packets.extend([[[2]], [[6]]])
|
packets.extend([[[2]], [[6]]])
|
||||||
sorted_packets = sorted(packets, key=cmp_to_key(packet_compare))
|
sorted_packets = sorted(packets, key=cmp_to_key(packet_compare))
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user