Skip to content

Commit

Permalink
Python: Replace Helpers.mult() with math.prod()
Browse files Browse the repository at this point in the history
  • Loading branch information
IsaacG committed Dec 13, 2024
1 parent f90d49b commit c49757f
Show file tree
Hide file tree
Showing 12 changed files with 32 additions and 34 deletions.
3 changes: 2 additions & 1 deletion 2015/d02.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"""Advent of Code: Day 02."""

import itertools
import math

from lib import aoc

Expand Down Expand Up @@ -33,5 +34,5 @@ def part2(self, puzzle_input: InputType) -> int:
total = 0
for dims in puzzle_input:
perimeters = [a + b for a, b in itertools.combinations(dims, 2)]
total += min(perimeters) * 2 + self.mult(dims)
total += min(perimeters) * 2 + math.prod(dims)
return total
2 changes: 1 addition & 1 deletion 2015/d20.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def part1_nope_a(self, puzzle_input: InputType) -> int:
pfactors = prime_factors(i)
factors = set(pfactors)
for l in range(2, len(pfactors)):
factors.update(self.mult(c) for c in itertools.combinations(pfactors, l))
factors.update(math.prod(c) for c in itertools.combinations(pfactors, l))

amount = sum(factors) + 1 + i
if amount >= target:
Expand Down
3 changes: 2 additions & 1 deletion 2015/d24.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"""Advent of Code, Day 24: It Hangs in the Balance. Balance numbers into groups with contraints."""

import itertools
import math

from lib import aoc

Expand All @@ -26,7 +27,7 @@ def balance(self, packages: list[int], groups: int) -> int:
for package_count in range(1, len(packages)):
for group in itertools.combinations(packages, package_count):
if sum(group) == group_size:
candidates.append(self.mult(group))
candidates.append(math.prod(group))
if candidates:
break
return min(candidates)
Expand Down
3 changes: 2 additions & 1 deletion 2019/d08.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""

import collections
import math
import more_itertools

from lib import aoc
Expand Down Expand Up @@ -44,4 +45,4 @@ def part2(self, puzzle_input: str) -> int:
# Displays the actual solution.
# print('\n'.join(out))
# Meaningless number to use in the solutions file.
return self.mult(sum(True for i in row if i != ' ') for row in out)
return math.prod(sum(True for i in row if i != ' ') for row in out)
3 changes: 2 additions & 1 deletion 2020/d16.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python
"""Train tickets."""

import math
from lib import aoc

# Fudge the second sample to include departure rows
Expand Down Expand Up @@ -133,4 +134,4 @@ def part2(self, data) -> int:
candidates.remove(column)

# Multiply all the fields that start with "departure".
return self.mult(v for k, v in completed_ticket.items() if k.startswith('departure'))
return math.prod(v for k, v in completed_ticket.items() if k.startswith('departure'))
3 changes: 2 additions & 1 deletion 2020/d20.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from lib import aoc
import collections
import enum
import math
from typing import Dict, List, Tuple
import data

Expand Down Expand Up @@ -290,7 +291,7 @@ def part1(self, blocks: List[str]) -> int:
# Four corners. Top left, top right, bottom left, bottom right.
line = list(range(4))
corners = zip(line, line[1:] + line[:1])
return self.mult(
return math.prod(
self.find_corner(tiles, corner)
for corner in corners
)
Expand Down
3 changes: 2 additions & 1 deletion 2021/d09.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/bin/python
"""Advent of Code: Day 09."""

import math
from lib import aoc

SAMPLE = ["""\
Expand Down Expand Up @@ -46,4 +47,4 @@ def part2(self, puzzle_input: aoc.Map) -> int:
basins = aoc.partition_regions(unexplored, predicate=lambda a, b: True)
basin_sizes = (len(basin) for basin in basins)

return aoc.Helpers.mult(sorted(basin_sizes, reverse=True)[:3])
return math.prod(sorted(basin_sizes, reverse=True)[:3])
3 changes: 2 additions & 1 deletion 2022/d08.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/bin/python
"""Advent of Code, Day 8: Treetop Tree House. Compute tree visibility."""

import math
from lib import aoc

SAMPLE = [
Expand Down Expand Up @@ -73,6 +74,6 @@ def part2(self, puzzle_input: aoc.Map) -> int:
break
cur += direction
visible.append(num)
scores.append(self.mult(visible))
scores.append(math.prod(visible))

return max(scores)
2 changes: 1 addition & 1 deletion 2022/d11.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def solver(self, monkeys: list[Monkey], part_one: bool) -> int:
monkeys[next_monkey].items.append(item)
monkey.items = []
inspected = sorted(monkey.inspected for monkey in monkeys)
return self.mult(inspected[-2:])
return math.prod(inspected[-2:])

def input_parser(self, puzzle_input: str) -> InputType:
"""Parse the input data."""
Expand Down
5 changes: 3 additions & 2 deletions 2022/d13.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import functools
import json
import math
from typing import Any

from lib import aoc
Expand Down Expand Up @@ -35,7 +36,7 @@
InputType = list[list[Any]]

# cmp for integers.
int_cmp = aoc.Helpers.cmp
int_cmp = aoc.cmp


def cmp(first: Any, second: Any) -> int:
Expand Down Expand Up @@ -87,4 +88,4 @@ def part2(self, puzzle_input: InputType) -> int:
for pair in pairs:
vals.extend(pair)
vals.sort(key=functools.cmp_to_key(cmp))
return self.mult(vals.index(divider) + 1 for divider in dividers)
return math.prod(vals.index(divider) + 1 for divider in dividers)
3 changes: 2 additions & 1 deletion 2022/d19.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/bin/python
"""Advent of Code, Day 19: Not Enough Minerals."""

import math
import re

from lib import aoc
Expand Down Expand Up @@ -140,7 +141,7 @@ def part1(self, puzzle_input: InputType) -> int:
return sum(idx * score for idx, score in enumerate(scores, start=1))

def part2(self, puzzle_input: InputType) -> int:
return self.mult(self.simulator(puzzle_input[:3], 32))
return math.prod(self.simulator(puzzle_input[:3], 32))

def input_parser(self, puzzle_input: str) -> InputType:
"""Parse the input data."""
Expand Down
33 changes: 11 additions & 22 deletions pylib/aoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ def render(points: set[complex], off: str = COLOR_EMPTY, on: str = COLOR_SOLID)
return "\n".join(rows)


def sign(number: int) -> int:
def sign(number: float) -> int:
"""Return the "sign" of a number, i.e. 1 or -1."""
if number > 0:
return 1
Expand All @@ -368,6 +368,16 @@ def sign(number: int) -> int:
return 0


def cmp(a: float, b: float) -> int:
"""Compare two numbers like Perl <=>.
Binary "<=>" returns -1, 0, or 1 depending on whether the left argument
is numerically less than, equal to, or greater than the right argument.
"""
return sign(a - b)



def reading_order(data: Sequence[complex]) -> list[complex]:
return sorted(data, key=lambda x: (x.imag, x.real))

Expand Down Expand Up @@ -433,27 +443,6 @@ class Helpers:
_primes = [2, 3, 5]
_gcd: dict[tuple[int, int], int] = {}

@staticmethod
def cmp(a: float, b: float) -> int:
"""Compare two numbers like Perl <=>.
Binary "<=>" returns -1, 0, or 1 depending on whether the left argument
is numerically less than, equal to, or greater than the right argument.
"""
if a < b:
return -1
if a > b:
return +1
return 0

@staticmethod
def mult(nums: Iterable[int]) -> int:
"""Product of all values. Like sum() but with multiplication."""
p = 1
for n in nums:
p *= n
return p

@staticmethod
def sum_map(lines: List[str], func: Callable[[str], int]) -> int:
"""sum_map(lines, func)"""
Expand Down

0 comments on commit c49757f

Please sign in to comment.