简体   繁体   中英

Making Range Function Act Over Given Values in Python

I would like to know if there is a way to make the range function act only over some given values.

I'm trying to write some code for Problem 2 of Project Euler where I must find the sum of the even-valued terms of the Fibonacci sequence whose values do not exceed 4,000,000.

My code at the moment looks like this:

#Fibonacci Even Sum

even_sum = 0 

def fib(n):

    a, b = 1,2
    while a < n:
        print (a)
        a, b = b, a + b
    print ()
    return a

for i in range(fib(4000000)):
    if i % 2 == 0:
        even_sum = i + even_sum

print (even_sum)

The problem seems to be that my code adds up all the even numbers up to 3524578, not just the even Fibonacci numbers. How can I change this?

Many thanks !

You should use a generator function, range() does not suit your problem. You can convert your fib function to a generator by giving yield a inside the while loop, that would make the function keep spitting out fibonacci numbers till n and you can find sum like that.

Example of generator -

>>> def fib(n):
...     a, b = 1,2
...     while a < n:
...             yield a
...             a, b = b, a+b
...
>>>
>>>
>>>
>>> for i in fib(200):
...     print(i)
...
1
2
3
5
8
13
21
34
55
89
144

you can make similar changes to your function.

Code would look like -

even_sum = 0 

def fib(n):

    a, b = 1,2
    while a < n:
        print (a)
        a, b = b, a + b
        yield a

for i in fib(4000000):
    if i % 2 == 0:
        even_sum = i + even_sum

print (even_sum)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM