1

I am trying to improve my programming skills by writing functions in multiple ways, this teaches me new ways of writing code but also understanding other people's style of writing code. Below is a function that calculates the sum of all even numbers in a fibonacci sequence up to the max value. Do you have any recommendations on writing this algorithm differently, maybe more compactly or more pythonic?

def calcFibonacciSumOfEvenOnly():
    MAX_VALUE = 4000000
    sumOfEven = 0
    prev = 1
    curr = 2


    while curr <= MAX_VALUE:
        if curr % 2 == 0:
            sumOfEven += curr

        temp = curr
        curr += prev
        prev = temp

    return sumOfEven

I do not want to write this function recursively since I know it takes up a lot of memory even though it is quite simple to write.

1 Answer 1

1

You can use a generator to produce even numbers of a fibonacci sequence up to the given max value, and then obtain the sum of the generated numbers:

def even_fibs_up_to(m):
    a, b = 0, 1
    while a <= m:
        if a % 2 == 0:
            yield a
        a, b = b, a + b

So that:

print(sum(even_fibs_up_to(50)))

would output: 44 (0 + 2 + 8 + 34 = 44)

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant - Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.