The crabs don’t seem interested in your proposed solution. Perhaps you misunderstand crab engineering?
As it turns out, crab submarine engines don’t burn fuel at a constant rate. Instead, each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1
, the second step costs 2
, the third step costs 3
, and so on.
As each crab moves, moving further becomes more expensive. This changes the best horizontal position to align them all on; in the example above, this becomes 5
:
16
to 5
: 66
fuel1
to 5
: 10
fuel2
to 5
: 6
fuel0
to 5
: 15
fuel4
to 5
: 1
fuel2
to 5
: 6
fuel7
to 5
: 3
fuel1
to 5
: 10
fuel2
to 5
: 6
fuel14
to 5
: 45
fuelThis costs a total of 168
fuel. This is the new cheapest possible outcome; the old alignment position (2
) now costs 206
fuel instead.
Determine the horizontal position that the crabs can align to using the least fuel possible so they can make you an escape route! How much fuel must they spend to align to that position? Determine this in the following way:
fuel
that takes the pathname (str
) of a text file containing the horizontal positions of each crab in a swarm. The function must return the least amount of fuel (int
) needed to align all crabs in the same horizontal position.In this interactive session we assume the text files positions01.txt
1 and positions02.txt
2 to be located in the current directory.
>>> fuel('positions01.txt')
168
>>> fuel('positions02.txt')
98363777