Python中从a到b的偶数之和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13809159/
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 09:40:32  来源:igfitidea点击:

Sum of even integers from a to b in Python

pythonpython-3.x

提问by knd15

This is my code:

这是我的代码:

def sum_even(a, b):
    count = 0
    for i in range(a, b, 1):
        if(i % 2 == 0):
            count += [i]
        return count

An example I put was print(sum_even(3,7)) and the output is 0. I cannot figure out what is wrong.

我放的一个例子是 print(sum_even(3,7)) 并且输出是 0。我不知道出了什么问题。

采纳答案by sampson-chen

Your indentation is off, it should be:

您的缩进已关闭,它应该是:

def sum_even(a, b):
    count = 0
    for i in range(a, b, 1):
        if(i % 2 == 0):
            count += i
    return count

so that return countdoesn't get scoped to your for loop (in which case it would return on the 1st iteration, causing it to return 0)

所以return count它不会被限定在你的 for 循环中(在这种情况下它会在第一次迭代时返回,导致它返回 0)

(And change [i]to i)

(并更改[i]i



NOTE:another problem - you should be careful about using range:

注意:另一个问题 - 你应该小心使用range

>>> range(3,7)
[3, 4, 5, 6]

so if you were to do calls to:

因此,如果您要拨打以下电话:

  • sum_even(3,7)
  • sum_even(3,8)
  • sum_even(3,7)
  • sum_even(3,8)

right now, they would both output 10, which is incorrect for sum of even integers between 3 and 8, inclusive.

现在,他们都会输出10,这对于 3 到 8 之间的偶数之和是不正确的,包括。

What you really want is probably this instead:

你真正想要的可能是这个:

def sum_even(a, b):
    return sum(i for i in range(a, b + 1) if i % 2 == 0)

回答by krlmlr

Indentation matters in Python. The code you write returns after the first item processed.

缩进在 Python 中很重要。您编写的代码在第一个项目处理后返回。

回答by arshajii

  1. Move the returnstatement out of the scope of the forloop (otherwise you will return on the first loop iteration).

  2. Change count += [i]to count += i.

  1. return语句移出for循环范围(否则您将在第一次循环迭代时返回)。

  2. 更改count += [i]count += i



Also (not sure if you knew this), range(a, b, 1)will contain all the numbers from ato b - 1(not b). Moreover, you don't need the 1argument: range(a,b)will have the same effect. So to contain all the numbers from ato byou should use range(a, b+1).

此外(不确定您是否知道这一点),range(a, b, 1)将包含从ab - 1(不b)的所有数字。此外,您不需要1参数:range(a,b)将具有相同的效果。因此,要包含从ato 的所有数字,b您应该使用range(a, b+1).

Probably the quickest way to add all the even numbers from ato bis

将所有偶数从ato相加的最快方法可能b

sum(i for i in xrange(a, b + 1) if not i % 2)

回答by Jeremy D

def sum_even(a,b):
    count = 0
    for i in range(a, b):
        if(i % 2 == 0):
            count += i
     return count

Two mistakes here :

这里有两个错误:

  • add i instead of [i]
  • you return the value directly at the first iteration. Move the return count out of the for loop
  • 添加 i 而不是 [i]
  • 您在第一次迭代时直接返回值。将返回计数移出 for 循环

回答by Matthew Strawbridge

You don't need the loop; you can use simple algebra:

你不需要循环;你可以使用简单的代数:

def sum_even(a, b):
    if (a % 2 == 1):
        a += 1
    if (b % 2 == 1):
        b -= 1
    return a * (0.5 - 0.25 * a) + b * (0.25 * b + 0.5)

Edit:

编辑:

As NPE pointed out, my original solution above uses floating-point maths. I wasn't too concerned, since the overhead of floating-point maths is negligible compared with the removal of the looping (e.g. if calling sum_even(10, 10000)). Furthermore, the calculations use (negative) powers of two, so shouldn't be subject by rounding errors.

正如 NPE 指出的那样,我上面的原始解决方案使用浮点数学。我并不太担心,因为与去除循环(例如,如果调用sum_even(10, 10000))相比,浮点数学的开销可以忽略不计。此外,计算使用 2 的(负)幂,因此不应受到舍入误差的影响。

Anyhow, with the simple trick of multiplying everything by 4 and then dividing again at the end we can use integers throughout, which is preferable.

无论如何,通过将所有内容乘以 4 然后在最后再次除以的简单技巧,我们可以始终使用整数,这是更可取的。

def sum_even(a, b):
    if (a % 2 == 1):
        a += 1
    if (b % 2 == 1):
        b -= 1
    return (a * (2 - a) + b * (2 + b)) // 4

回答by Santiclause

You can make it far simpler than that, by properly using the step argument to the range function.

通过正确使用 range 函数的 step 参数,您可以使其简单得多。

def sum_even(a, b):
    return sum(range(a + a%2, b + 1, 2))

回答by Artur

I'd like you see how your loops work if b is close to 2^32 ;-) As Matthew said there is no loop needed but he does not explain why.

如果 b 接近 2^32,我希望你看看你的循环是如何工作的;-) 正如马修所说,不需要循环,但他没有解释原因。

The problem is just simple arithmetic sequence wiki. Sum of all items in such sequence is:

问题只是简单的等差数列wiki。该序列中所有项目的总和为:

      (a+b)  
Sn = ------- * n  
        2  

where 'a' is a first item, 'b' is last and 'n' is number if items. If we make 'a' and b' even numbers we can easily solve given problem. So making 'a' and 'b' even is just:

其中“a”是第一个项目,“b”是最后一个,“n”是项目的编号。如果我们将 'a' 和 b' 设为偶数,我们就可以轻松解决给定的问题。所以使 'a' 和 'b' 甚至只是:

if ((a & 1)==1):
    a = a + 1
if ((b & 1)==1):
    b = b - 1

Now think how many items do we have between two even numbers - it is:

现在想想我们在两个偶数之间有多少项 - 它是:

    b-a
n = --- + 1
     2 

Put it into equation and you get:

把它代入方程,你得到:

      a+b       b-a 
Sn = ----- * ( ------ + 1)
       2         2

so your code looks like:

所以你的代码看起来像:

def sum_even(a,b):
    if ((a & 1)==1):
        a = a + 1
    if ((b & 1)==1):
        b = b - 1
    return ((a+b)/2) * (1+((b-a)/2))

Of course you may add some code to prevent a be equal or bigger than b etc.

当然,您可以添加一些代码来防止 a 等于或大于 b 等。

回答by Mesut014

The sumof all the evennumbers between the startand endnumber (inclusive).

起始数和结束数()之间所有偶数总和

 def addEvenNumbers(start,end):
  total = 0
  if end%2==0:
    for x in range(start,end):
      if x%2==0:
        total+=x
    return total+end
  else:
    for x in range(start,end):
      if x%2==0:
        total+=x
    return total
print addEvenNumbers(4,12)

回答by Deepwinter

This might be a simple way of doing it using the range function. the third number in range is a step number, i.e, 0, 2, 4, 6...100

这可能是使用 range 函数的一种简单方法。范围内的第三个数字是步数,即 0, 2, 4, 6...100

sum = 0
for even_number in range(0,102,2):
    sum += even_number
print (sum)

回答by Poseidon_Geek

little bit more fancy with advanced python feature.

高级 python 功能更花哨。

def sum(a,b):
    return a + b
def evensum(a,b):
    a = reduce(sum,[x for x in range(a,b) if x %2 ==0])
    return a