Counter().most_common() is twice as fast as searching in a for-loop

This commit is contained in:
Stefan Harmuth 2022-01-17 09:38:18 +01:00
parent 8552731beb
commit 77dd1077e5
2 changed files with 6 additions and 6 deletions

View File

@ -1,4 +1,4 @@
from collections import defaultdict from collections import Counter
from itertools import combinations from itertools import combinations
from tools.aoc import AOCDay from tools.aoc import AOCDay
from tools.coordinate import Coordinate, DistanceAlgorithm from tools.coordinate import Coordinate, DistanceAlgorithm
@ -17,7 +17,7 @@ ROTATION_PATH = [
def overlap(beacon1: Grid, beacon2: Grid) -> Union[Coordinate, None]: def overlap(beacon1: Grid, beacon2: Grid) -> Union[Coordinate, None]:
diffs = defaultdict(int) diffs = Counter()
for c1 in beacon1.getActiveCells(): for c1 in beacon1.getActiveCells():
for c2 in beacon2.getActiveCells(): for c2 in beacon2.getActiveCells():
# Interestingly adding an if statement here to break out early when already 12 matches are found # Interestingly adding an if statement here to break out early when already 12 matches are found
@ -25,9 +25,9 @@ def overlap(beacon1: Grid, beacon2: Grid) -> Union[Coordinate, None]:
# and checking the results afterwards. # and checking the results afterwards.
diffs[c1 - c2] += 1 diffs[c1 - c2] += 1
for d in diffs: d = diffs.most_common(1)[0]
if diffs[d] >= 12: if d[1] >= 12:
return d return d[0]
def converge(scanner_grids: List[Grid]) -> (Grid, List[Coordinate]): def converge(scanner_grids: List[Grid]) -> (Grid, List[Coordinate]):

View File

@ -8,7 +8,7 @@ def getTheNumberFast(pushpull, adders, subbers, part2=False):
inc = 1 inc = 1
else: else:
number_init = [9] * 14 number_init = [9] * 14
inc = - 1 inc = -1
z = int(1e9) z = int(1e9)
number = number_init.copy() number = number_init.copy()