python - 使用 Python 对 1000 以下的 3 和 5 的倍数求和
问题描述
我编写了一个程序,旨在找到 1000 以下的所有 3 和 5 的倍数之和。我得到的输出是266333
,但这不是正确的答案。请帮忙,这是我的代码:
x = 3
y = 5
x_list = []
y_list = []
while x < 1000:
x_list.append(x)
x += 3
while y < 1000:
y_list.append(y)
y += 5
numsum = sum(x_list + y_list)
print(numsum)
解决方案
The issue here is that you're adding all of the numbers which are multiples of 3 and all of the numbers that are multiples of 5, which includes the numbers that are multiples of both (e.g. 15
, 30
, 45
, etc.) twice.
To simplify, let's look at the same problem, but with the multiples of 3 & 5 below 20.
After modifying the while loops to while x < 20
& while y < 20
respectively, we would end up with these two lists:
x_list = [3, 6, 9, 12, 15, 18]
y_list = [5, 10, 15]
The current code sum(x_list + y_list)
equates to sum([3, 6, 9, 12, 15, 18, 5, 10, 15])
, which gives us 93
, but if you look closely, this includes 15 twice because it's a multiple of both 3 & 15, which we don't want.
What we want to do here, is to remove all duplicates from the x_list + y_list
list, however there's no need to iterate through the lists and remove duplicates, because Python has a data type designed for this called a set
. A set is defined in the Python documentation as "Unordered collections of unique elements", and while it may not store the order of elements within it (which can make a difference in some situations), we're just trying to not have duplicates so we can get the right sum, so we don't care what order they're in.
Continuing the simplified example, set(x_list + y_list)
equates to sum({3, 5, 6, 9, 10, 12, 15, 18})
which you may notice only includes 15
once, and gives us 78
, which is 15 less than 93
.
Therefore, your second to last line should instead read numsum = sum(set(x_list + y_list))
, which in the original situation (summing multiples of 3 & 5 below 1000) will give you 233168
. Counting all those duplicates caused the calculation to be off by 33165
.
Note: While I found this solution independently, it had previously been mentioned in the comments by Prune
推荐阅读
- javascript - 甜蜜警报 - 按钮 ID
- javascript - Javascript中的变量可以不及时声明吗
- c# - 带有 AutoGenerateColumns 和 Cellbackground 的 C# wpf Datagrid
- vue.js - 如何创建一个动态 vue 组件,该组件的计算模板包含另一个具有 Object 属性的组件,而不将其作为字符串传递
- d3.js - d3.js - 理解 enter()
- css - Firefox 的 userChrome.css 中的 CSS 变量不生效
- reactjs - 在需要状态更改的代码运行后反应状态更新
- apache-camel - Camel - 使用 Camel Bindy 使用本地磁盘中的 CSV 丰富 FTP 中的 CSV
- java - 错误:未找到 Gradle DSL 方法:'Android()'
- javascript - 即使在 html 文件末尾使用我的脚本,Javascript querySelector 也无法正常工作