Python 总结 range() 中的所有整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20455977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:29:02  来源:igfitidea点击:

Sum up all the integers in range()

pythonpython-3.x

提问by mllnd

I need to write a program that sums up all the integers which can be divided by 3 in the range of 100 to 2000. I'm not even sure where to start, so far I've got this tiny piece of code written which isn't correct.

我需要编写一个程序,将 100 到 2000 范围内可以被 3 整除的所有整数相加。我什至不知道从哪里开始,到目前为止,我已经编写了一小段代码不正确。

for x in range(100, 2001, 3):
      print(x+x)

Any help is much appreciated!

任何帮助深表感谢!

采纳答案by aga

Use generator expression and sum function here:

在此处使用生成器表达式和 sum 函数:

res = sum(x for x in range(100, 2001) if x % 3 == 0)

It's pretty self-explanatory code: you're summing all the numbers from 100 to 2000, inclusive, which are divisible by three.

这是一段不言自明的代码:您要对 100 到 2000(含)之间的所有数字求和,这些数字可以被 3 整除。

回答by Deck

There is a sum function

有一个求和函数

>>> sum(filter(lambda x: x % 3 == 0, range(100, 2000)))
664650

But this is better:

但这更好:

>>> sum(x for x in range(100, 2000) if x % 3 == 0)
664650

回答by Inbar Rose

Since you know the first number in this range that is divisible by 3 is 102, you can do the following:

由于您知道此范围内第一个可被 3 整除的数字是 102,因此您可以执行以下操作:

Solution:

解决方案:

>>> sum(range(102, 2001, 3))
664650

To make it into a robust function:

使其成为一个健壮的函数:

def sum_range_divisible(start, end, divisor):
    while start % divisor != 0:
        start += 1
    return sum(range(start, end, divisor))

Using it:

使用它:

>>> sum_range_divisible(100, 2001, 3)
664650

Note:

笔记:

The advantage here is that you do not have to check each number in the whole range, since you are jumping by 3 each time.

这里的优点是您不必检查整个范围内的每个数字,因为您每次都跳 3。



Timing:

定时:

I have timed the different solutions, mine and aga's:

我已经为不同的解决方案计时,我的和aga 的

>>> import timeit
>>> timeit.Timer('sum(range(102, 2001, 3))').repeat()
[9.516391893850312, 9.49330620765817, 9.508695564438462]
>>> timeit.Timer('sum(x for x in range(100, 2001) if x % 3 == 0)').repeat()
[134.757627812011, 134.46399066622394, 138.34528734198346]

Conclusion:

结论:

My answer is faster by a factor of 14

我的回答快了14

回答by devil00

sum(filter(lambda l : l%3 ==0, range(100,2001)))

回答by Aristide

There is a closed formula for that.

有一个封闭的公式。

If (u_i) is a sequence defined by its first term u_0 and its common difference r, then the sum of the n first terms of (u_i) is:

如果 (u_i) 是由它的第一项 u_0 和它的公差 r 定义的序列,那么 (u_i) 的前 n 项之和是:

\frac{n(u_0 + u_{n-1})}{2}

\frac{n(u_0 + u_{n-1})}{2}

EDIT: I have made this little videoto explain it visually.

编辑:我制作了这个小视频来直观地解释它。

A popular anecdoteattributes this formula to the young Johann Carl Friedrich Gauss.

一个流行的轶事将这个公式归功于年轻的约翰·卡尔·弗里德里希·高斯。

In your case:

在你的情况下:

  • u_0 = 102
  • u_{n-1} = 1998
  • n = (1998 - 102) / 3 + 1 = 633
  • u_0 = 102
  • u_{n-1} = 1998
  • n = (1998 - 102) / 3 + 1 = 633

So, the sum is (633 * (102 + 1998)) / 2 = 664650.

所以,总和是 (633 * (102 + 1998)) / 2 = 664650。

As a general Python function with the usual rangearguments start, stop, step:

作为带有常用range参数start, stop,的通用 Python 函数step

def arithmetic_series(start, stop, step):
    number_of_terms = (stop - start) // step
    sum_of_extrema = start + (stop - step)
    return number_of_terms * sum_of_extrema // 2

In your case, the call would be:

在您的情况下,电话将是:

arithmetic_series(102, 2001, 3)

The complexity is O(1) instead of O(n), so unsurprisingly:

复杂度是 O(1) 而不是 O(n),所以不出所料:

%timeit sum(range(102, 2001, 3))
100000 loops, best of 3: 17.7 μs per loop

%timeit arithmetic_series(102, 2001, 3)
1000000 loops, best of 3: 548 ns per loop