[英]What's wrong in this simple python code?
Why is it not giving out correct total of first even fibonacci numbers upto 4 mn? 为什么它没有给出正确的第一个甚至斐波纳契数最多达到400万的总数?
x = 1
y = 2
list = [1,2]
while y< 4000000:
z= x+y
x=y
y=z
list.append (y)
list_even = []
for a in list:
if a%2 == 0:
list_even.append (a)
else:
pass
total = sum(list_even)
print (total)
There are other answers already addressing specific bugs in your code, so I want to offer a completely different implementation that achieves your stated goal: 还有其他答案已经解决了代码中的特定错误,所以我想提供一个完全不同的实现来实现您的既定目标:
giving out correct total of first even fibonacci numbers upto 4 mn
给出正确的第一个甚至斐波纳契数的总数高达4百万
If you want to find the sum of the even Fibonacci numbers up to some limit, the code below might be a more functional way of achieving it. 如果你想找到偶数Fibonacci数的总和达到某个极限,下面的代码可能是实现它的更实用的方法。 It's based on composing Python generators, which should help make the code easier to follow and more reusable.
它基于组合Python生成器,这应该有助于使代码更容易遵循和更可重用。
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def evens(l):
for x in l:
if x % 2 == 0:
yield x
def sum_even_fibonacci(limit):
total = 0
for x in evens(fib()):
if total + x > limit:
return total
total += x
if __name__ == '__main__':
print(sum_even_fibonacci(4000000))
Output 产量
1089154
Edit 编辑
It's ambiguous what exactly OP is asking. 确切地说OP正在问什么是模棱两可的。
If OP wants to sum the even Fibonacci terms until the sum would surpass 4,000,000 , then the answer is what I stated above - 1089154. 如果OP希望总和甚至斐波纳契项, 直到总和超过4,000,000 ,那么答案就是我上面所说的 - 1089154。
If OP wants to sum all even Fibonacci terms under 4,000,000 , then the expression if total + x > limit
would change to x > limit
and the answer would be 4613732. 如果OP希望将所有均匀的Fibonacci项加在4,000,000以下 ,则表达式
if total + x > limit
将更改为x > limit
并且答案将为4613732。
I recognize this as Problem 2 on Project Euler. 我认为这是项目欧拉的问题2 。 For some reason, @Tagc is getting the wrong answer.
出于某种原因,@ Tagc得到了错误的答案。 I used a generator as well but not a list.
我也使用了发电机而不是列表。 Here was my solution:
这是我的解决方案:
def fibonacci():
term_0, term_1 = 1,2
while True:
yield term_0 + term_1
term_0, term_1 = term_1, term_0 + term_1
fibonacci_sum = 2
for n in fibonacci():
if n > 4000000: break
if n % 2 == 0: fibonacci_sum += n
print(fibonacci_sum)
Output: 输出:
$ python 002.py
4613732
just for fun, this is an one liner version 只是为了好玩,这是一个单线版本
from itertools import takewhile
def fib():
fk, fk1 = 0,1
while True:
yield fk
fk, fk1 = fk1, fk+fk1
print( sum( x for x in takewhile(lambda f:f<4000000,fib()) if x%2==0 ) )
here takewhile will stop the iteration when the condition is no longer satisfied the same way as the others answers 这里takewhile将停止迭代,当条件不再满足时,与其他答案相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.