From fb8a911d4df72cf188d781ffdd24e5ede08c6426 Mon Sep 17 00:00:00 2001 From: Mikael CAPELLE Date: Wed, 6 Dec 2023 08:47:59 +0100 Subject: [PATCH] Clean 2023. --- 2023/day2.py | 8 +++----- 2023/day6.py | 39 ++++++++++++++++----------------------- 2 files changed, 19 insertions(+), 28 deletions(-) diff --git a/2023/day2.py b/2023/day2.py index f4db8ed..a768318 100644 --- a/2023/day2.py +++ b/2023/day2.py @@ -1,6 +1,5 @@ -import operator +import math import sys -from functools import reduce from typing import Literal, TypeAlias, cast CubeType: TypeAlias = Literal["red", "blue", "green"] @@ -36,9 +35,8 @@ print(f"answer 1 is {answer_1}") # part 2 answer_2 = sum( - reduce( - operator.mul, - (max(cube_set.get(cube, 0) for cube_set in set_of_cubes) for cube in MAX_CUBES), + math.prod( + max(cube_set.get(cube, 0) for cube_set in set_of_cubes) for cube in MAX_CUBES ) for set_of_cubes in games.values() ) diff --git a/2023/day6.py b/2023/day6.py index 0c4a864..3290b8a 100644 --- a/2023/day6.py +++ b/2023/day6.py @@ -1,22 +1,16 @@ -import operator +import math import sys -from functools import reduce - -lines = sys.stdin.read().splitlines() def extreme_times_to_beat(time: int, distance: int) -> tuple[int, int]: - import math - - # formula - # - distance = (T - t) * t - # - (T - t) * t >= D - # - T * t - t^2 - D >= 0 - - a = -1 - b = time - c = -distance + # formula (T = total time, D = target distance) + # - speed(t) = t, + # - distance(t) = (T - t) * speed(t) + # - distance(t) > D + # <=> (T - t) * t > D + # <=> -t^2 + T * t - D >= 0 + a, b, c = -1, time, -distance d = b * b - 4 * a * c t1 = math.ceil(-(b - math.sqrt(d)) / (2 * a)) @@ -31,18 +25,17 @@ def extreme_times_to_beat(time: int, distance: int) -> tuple[int, int]: return t1, t2 +lines = sys.stdin.read().splitlines() + # part 1 times = list(map(int, lines[0].split()[1:])) distances = list(map(int, lines[1].split()[1:])) -answer_1 = reduce( - operator.mul, - ( - t2 - t1 + 1 - for t1, t2 in ( - extreme_times_to_beat(time, distance) - for time, distance in zip(times, distances) - ) - ), +answer_1 = math.prod( + t2 - t1 + 1 + for t1, t2 in ( + extreme_times_to_beat(time, distance) + for time, distance in zip(times, distances) + ) ) print(f"answer 1 is {answer_1}")