Python Forum

Full Version: Fibonacci sequence problem is confusing me
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am having a hard time initiating this program

The idea of the Fibonacci sequence can be generalized by starting with any two numbers F0 and F1, and then continuing as in the Fibonacci sequence so that Fn = Fn-1 + Fn-2 for n>=2.

Use the Design Recipe to define a function gen_fibonacci that consumes three integer arguments. The first two arguments are the first two members of the sequence, and the third is the number of elements to print, each on its own line. Include a docstring!
For example:

Test



Displays

gen_fibonacci(2,5,5)



2
5
7
12
19


I started like this :
def gen_fibonacci(n,n2,n3):
    f1 = 0
    f2 = 1
    if n >= 1:
        print(f1)
    if n >= 2:
        print(f2)
    for i in range(2, n):
      
thank you
You are on the right track, now the for loop needs some code.
In each iteration, print the new value (sum of f1 and f2) and assign new values to f1 and f2 accordingly.
With homework its always good to start with defining problem in spoken language. As far as I understand:

- give me fibonacci sequence of defined length calculated based on two first sequence elements provided

Every element in fibonacci sequence is sum of its previous two elements. Function provides two first elements, therefore finding third element is as simple as first + second. The only problem is how to renew values to find next and to be sure that number of elements in sequence is correct.

As this is homework and name of the function (gen_) calls it following example is using generator function. Presumably you can't use this code directly but you can get general idea and modify it to fit your needs (NB! Code is not defensive i.e in case of length 0 and 1 it will not give sequence of correct length).

def gen_fibonacci(first, second, length):
    yield first
    yield second
    for i in range(length - 2):
        current = first + second
        yield current
        first, second = second, current

print(*gen_fibonacci(2, 5, 5), sep='\n')
2
5
7
12
19