gpt4 book ai didi

python - Advent of Code 2019 第 1 天 : What's wrong with my math/logic?

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:36 25 4
gpt4 key购买 nike

以下是 Advent of Code 2019 第 1 天第 1 部分的提示:

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?

这是我尝试的两个版本:

'''
Simplification:

total fuel = (m1 / 3 - 2) + (m2 / 3 - 2) + (m3 / 3 - 2) + ... + (mn / 3 - 2)

total fuel = (m1 / 3) + (m2 / 3) + ... + (mn / 3) - 2 - 2 - ... - 2

total fuel = (1 / 3)(m1 + ... + mn) - 2 * n
'''

# Why doesn't this work?
print(sum(masses) // 3 - 2 * len(masses))

# This works, though...
print(sum([m // 3 - 2 for m in masses]))

第一次打印输出 3384266,而第二次输出 3384232,即正确答案。

那么...第一个版本到底出了什么问题?

最佳答案

区别在于四舍五入,您的简化没有考虑到这一点。

考虑以下(两个重量为 2 的单位(是的,它们会变为负数,但暂时忽略 - 2)):

>>> (2 // 3 + 2 // 3)
0
>>> (2 + 2) // 3
1

关于python - Advent of Code 2019 第 1 天 : What's wrong with my math/logic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59132152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com