As always, a warm-up excersice to start with. For me, it's the time of finding my aoc repository and upgrading all my packages first. :-)
import aocd
data = aocd.get_data(day=1, year=2019)
modules = list(map(int, data.splitlines()))
def fuel_requirement(mass: int) -> int:
return mass // 3 - 2
tests = {
12: 2,
14: 2,
1969: 654,
100756: 33583,
}
for mass, expected in tests.items():
assert (
fuel_requirement(mass) == expected
), f"fuel_requirement({mass}) = {fuel_requirement(mass)} vs. {expected}"
print("Part 1:", sum(map(fuel_requirement, modules)))
Part 1: 3346639
Part two adds a little iteration; make sure to add to the total only if the new requirement is larger than 0!
def iterative_fuel_calc(mass: int) -> int:
total = 0
requirement = fuel_requirement(mass)
while requirement > 0:
total += requirement
requirement = fuel_requirement(requirement)
return total
tests = {
14: 2,
1969: 966,
100756: 50346,
}
for mass, expected in tests.items():
assert (
iterative_fuel_calc(mass) == expected
), f"iterative_fuel_calc({mass}) = {iterative_fuel_calc(mass)} vs. {expected}"
print("Part 2:", sum(map(iterative_fuel_calc, modules)))
Part 2: 5017110