嘿,所以我正在尝试将 1000 以内 3 或 5 的倍数的每个数字相加,当我输入此代码时:
Hey so I'm trying to do a challenge to add every number in multiples of 3 or 5 under 1000, and when I put in this code:
for x in xrange(1000): if x % 3 == 0 or x % 5 == 0: place = list([x]) sum(place)它只是列出了 3 和 5 的倍数的所有数字,有什么办法可以将它列出的所有数字相加吗?
it just lists all the numbers that are multiples of 3 and 5, is there any way I can add all the numbers that it lists?
推荐答案您的问题是您没有在循环的每次迭代中保留任何值.您的循环将通过以下方式修复:
Your issue is you are not retaining any value through each iteration of your loop. Your loop would be fixed with:
place = [] for x in range(1000): if x % 3 == 0 or x % 5 == 0: place.append(x) sum(place)或者只是沿途计算:
result = 0 for x in range(1000): if x % 3 == 0 or x % 5 == 0: result += x result正如所指出的,一个简单的生成器表达式可以解决这个问题:
As pointed out, a simple generator expression would solve the problem:
sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0)注意:我使用 Py3 - 在 Py2 中 xrange() 将通过避免 range() 的 list 构造来优化.
Note: I use Py3 - in Py2 xrange() would be an optimisation by avoiding the list construction of range().
但是sum(range(n+1))有一个封闭形式:
s(n) = n * (n + 1) // 2例如:
sum([0, 1, 2, 3, ..., 999]) == 999 * 1000 // 2 == 499500可以扩展为 sum(range(0, n+1, c)) 为:
s(n, c) = c * (n//c) * (n//c + 1) // 2例如:
sum([0, 3, 6, 9, ..., 999]) == 3 * (999//3) * (999//3 + 1) // 2 == 166833所以你可以把问题改写为s(999, 3) + s(999, 5) - s(999, 15),你必须减去s(999, 15) 或者您重复计算所有可以被 3 和 5 整除的值,例如:
So you can rewrite the problem as s(999, 3) + s(999, 5) - s(999, 15), you must subtract s(999, 15) or you double count all the values that are divisible by both 3 and 5, e.g.:
In []: n = 1000 s = lambda n, c: c * (n//c) * (n//c + 1) // 2 s(n-1, 3) + s(n-1, 5) - s(n-1, 15) Out[]: 233168对于所有提出的各种 sum 方法,这是 O(1) 与 O(n).
This is O(1) vs O(n) for all the various sum approaches proposed.
更多推荐
如何在一个范围内添加数字
发布评论