Wednesday, 12 May 2021

Generator: squaring the nth fibonacci number

 

def fibonacci_numbers(nums):
    x, y = 0, 1 #setting the starting values for the fibonacci sequence
    for _ in range(nums):
        x, y = y, x+y #new value function to run up until it completes the range specified.
        yield x #take the value of the x from the operation ran until range.

def square(nums):
    for num in nums: #take the result from the previous x
        yield num**2 #square the x

print(sum(square(fibonacci_numbers(10))))

No comments:

Post a Comment