4
\$\begingroup\$

Advent of Code 2019: Day 1

I'm doing Advent of Code this year. Below is my attempt at day 1:

Problem

Part One

--- Day 1: The Tyranny of the Rocket Equation ---

Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.

Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!

The Elves quickly load you into a spacecraft and prepare to launch.

At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.

Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.

For example:

  • For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
  • For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
  • For a mass of 1969, the fuel required is 654.
  • For a mass of 100756, the fuel required is 33583.

The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.

What is the sum of the fuel requirements for all of the modules on your spacecraft?

 

Part Two

--- Part Two ---

During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence. Apparently, you forgot to include additional fuel for the fuel you just added.

Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing really hard, which has no mass and is outside the scope of this calculation.

So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example:

  • A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so the total fuel required is still just 2.
  • At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
  • The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.

What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)


Solution

f = lambda mass: mass // 3 - 2

def partial_sum(mass):
    return 0 if f(mass) <= 0 else f(mass) + partial_sum(f(mass))


def part_one():
    with open(r"../Inputs/day_1.txt") as file:
        return sum(f(int(i)) for i in file.readlines())

def part_two():
    with open(r"../Inputs/day_1.txt") as file:
        return sum(partial_sum(int(mass)) for mass in file.readlines())

Notes

I don't consider myself a beginner in Python, however I am not proficient in it either. I guess I would be at the lower ends of intermediate. I am familiar with PEP 8 and have read it in its entirety, thus, any stylistic deviations I make are probably deliberate. Nevertheless, feel free to point them out if you feel a particular choice of mine was sufficiently erroneous. I am concerned with best practices and readability, but also the performance of my code. I am not sure what tradeoff is appropriate, and would appreciate feedback on the tradeoffs I did make.

My style tends to over utilise functions. This is partly because I genuinely think separating functionality into functions is a good thing, but is also an artifiact of my development practices. I tend to write the program in a Jupyter notebook (the ability to execute arbitrary code excerpts in semi isolated cells is a very helpful development aid and lends itself naturally to one function per cell (with the added benefit of being able to easily test functions independently)). I would welcome thoughts on this, but unless it is particularly egregious, I am unlikely to change it.

\$\endgroup\$
3
  • \$\begingroup\$ Shouldn't partial_sum directly include mass in the sum? So return mass + (0 if f(mass) <=0 else f(mass) + partial_sum(f(mass)))? \$\endgroup\$
    – bob
    Dec 4, 2019 at 19:56
  • \$\begingroup\$ Can you do the math ahead of time and derive a closed-form equation for the total fuel required for a module based on a recurrence relation? I haven't tried it, so not sure it's possible. Otherwise I personally think the recursive approach makes more sense here than an iterative one (in general I prefer functional prog over imperative). \$\endgroup\$
    – bob
    Dec 4, 2019 at 20:01
  • \$\begingroup\$ "Shouldn't partial_sum directly include mass in the sum? So return mass + (0 if f(mass) <=0 else f(mass) + partial_sum(f(mass)))?" @bob no. That I posted it here means the solution works. Changing it as you described wouldn't work. The reason it starts with 0 is because the partial sum eventually drops below 0, so 0 forms the base case of the recursive algorithm. \$\endgroup\$ Dec 5, 2019 at 6:56

2 Answers 2

5
\$\begingroup\$
f = lambda mass: mass // 3 - 2

I would question the spec and consider making this max(0, mass // 3 - 2).


def partial_sum(mass):
    return 0 if f(mass) <= 0 else f(mass) + partial_sum(f(mass))

DRY: calculate f(mass) once and store it in a local variable.

partial_sum isn't the most descriptive name.


def part_one():
    with open(r"../Inputs/day_1.txt") as file:
        return sum(f(int(i)) for i in file.readlines())

def part_two():
    with open(r"../Inputs/day_1.txt") as file:
        return sum(partial_sum(int(mass)) for mass in file.readlines())

Again, DRY. This isn't as clear cut, but I think it's worth pulling out a function which takes a module mass and returns a total fuel mass, and then part_one calls it with f and part_two calls it with partial_sum.

Well done for using with for the file I/O.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the pointers re: my grouping into functions. I'll implement those. \$\endgroup\$ Dec 5, 2019 at 7:10
9
\$\begingroup\$

Your function f should probably be a proper function, like all the others. There is no reason for it to be a lambda.

def fuel(mass):
    return mass // 3 - 2

Instead of using recursion, you could use iteration in partial_sum:

def total_fuel(mass):
    total_mass = 0
    while True:
        mass = fuel(mass)
        if mass <= 0:
            break
        total_mass += mass
    return total_mass

The difference between the iterative and recursive approach is not really relevant here. The required fuel quickly vanishes even for really large masses (like 1e308), so you never run into the stack size limit. However, timing wise the iterative approach is faster by up to about a factor three, probably due to the overhead of the additional function calls of the recursive solution:

In [31]: %timeit partial_sum(1e308)
1.04 ms ± 9.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [32]: %timeit total_fuel(1e308)
372 µs ± 6.47 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In Python 3.8+ this function can be shortened a bit more, as mentioned in the comments by @409_Conflict:

def total_fuel(mass):
    total_mass = 0
    while (mass := fuel(mass)) > 0:
        total_mass += mass
    return total_mass

Files are directly iterable, there is no need to first read the whole file content into memory:

def part_two():
    with open("../Inputs/day_1.txt") as file:
        return sum(total_fuel(int(mass)) for mass in file)

Note that usually you don't need the string to be a raw string, a simple "" string suffices here.

You don't show in this case how you are calling it. but you should make sure to put it under a if __name__ == "__main__": guard to allow importing from this script without running the code.

It might also be worthwhile to add a docstring to each of your functions, or at least add a module docstring with the challenge description.

\$\endgroup\$
9
  • 2
    \$\begingroup\$ Python 3.8 FTW: while (mass := fuel(mass)) > 0: total_mass += mass \$\endgroup\$ Dec 4, 2019 at 13:34
  • \$\begingroup\$ @409_Conflict: Ah yes, I was trying to find a way to do that, but I always forget about the new walrus operator... \$\endgroup\$
    – Graipher
    Dec 4, 2019 at 13:35
  • \$\begingroup\$ Yeah, the new patterns to recognize are data = do_work(); if condition(data):... and its corollary using while True ... break. \$\endgroup\$ Dec 4, 2019 at 13:41
  • \$\begingroup\$ In your rocket_equation function, did you include the module's mass anywhere in the calculation of total_mass? I'm not seeing it but may have missed it? \$\endgroup\$
    – bob
    Dec 4, 2019 at 19:55
  • 1
    \$\begingroup\$ @bob Yeah. That is probably a better name for the function, edited. \$\endgroup\$
    – Graipher
    Dec 4, 2019 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.