开发者

Euler Project No. 2 with Python

开发者 https://www.devze.com 2022-12-17 01:07 出处:网络
Can somebody tell me why this should be wrong? #Each new term in the Fibonacci sequence is generated #by adding the previous two terms. By starting with 1 and 2,

Can somebody tell me why this should be wrong?

#Each new term in the Fibonacci sequence is generated
#by adding the previous two terms. By starting with 1 and 2,
#the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#Find the sum of all the even-valued terms in the sequence
#which do not exceed four million.


sum=2

list = [1,2]
for x in range开发者_运维知识库(2,100):
    a = list[x-2]+list[x-1]
    print(a)
    list.append(a)
    if a % 2 == 0:
        sum += a
        print('sum', sum)
        if sum >= 4000000:
            break


Here's a completely different way to solve the problem using a generator and itertools:

def fib():
    a = b = 1
    while 1:
        yield a
        a, b = b, a + b

import itertools
print sum(n for n in itertools.takewhile(
    lambda x: x <= 4000000, fib()) if n % 2 == 0)

Output:

4613732

So your code, even though it is wrong (see other answers), happens to give the correct answer.


replace

    sum += a
    print('sum', sum)
    if sum >= 4000000:
        break

with

    if a > 4000000:
        break
    sum += a
    print('sum', sum)

You should compare "a" with 4000000, not "sum", like Daniel Roseman said.


The question asked for the sum of even terms which do not exceed four million. You're checking if the sum doesn't exceed 4m.


I'm trying to solve the same problem - although I understand the logic to do it, I don't understand why this works (outputs the right sum)

limit = 4000000
s = 0

l = [1,2]
while l[-1]<limit:
    n = l[-1]+l[-2]
    l.append(n)
    print n

And then then moment I put in the modulo function, it doesn't output anything at all anymore.

limit = 4000000
s = 0

l = [1,2]
while l[-1]<limit:
    n = l[-1]+l[-2]
    if n % 2 == 0 :
        l.append(n)
        print n

I'm sure this is fairly simple...thanks!


This is the code I used. It is very helpful and teaches you about generators.

def fib():
        x,y = 0,1
        while True:
            yield x
            x,y = y, x+y

def even(seq):
    for number in seq:
        if not number % 2:
            yield number

def under_a_million(seq):
    for number in seq:
        if number > 4000000:
            break
        yield number   

print sum(even(under_a_million(fib())))

-M1K3


Keep it simple and it should take you less than 0.1 seconds.

from datetime import datetime
x, y = 1, 1
total = 0
for i in xrange (1, 100):
    x = x + y
    if x % 2 == 0 and x <= 4000000:
        total += x
    y = y + x
    if y % 2 == 0 and x <= 4000000:
        total += y

print total

starttime = datetime.now()
print datetime.now() - starttime
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号