0
def fibonacci(n):

    prev = curr = 1
    yield 1
    while curr < n:
        yield curr
        #1
        prev = curr 
        curr = curr + prev 
        #or
        #2
        prev ,curr = curr, curr + prev

I have this fibonacci code here and I don't understand why when I assign:

prev = curr #first
curr = curr + prev #second

fibonacci(10)

results: 11248

gives a different answer then when I assign

prev ,curr = curr, curr + prev 

fibonacci(10)

results: 112358

Which gives the correct Fibonacci sequence. Can someone please explain to me why is it so?

Thank you in advance for your input.

2
  • in this first one you're bascially doing curr = 2*curr Commented Oct 13, 2021 at 11:40
  • 1
    Try to go line by line and write on paper the values of curr and prev in each step. Or add some debug/print lines Commented Oct 13, 2021 at 11:43

2 Answers 2

1

what prev, curr = curr, prev+ curr does is similar to:

temp = prev + curr
prev = curr
curr = temp

But what you are doing is setting curr value to prev and then you are basically doing curr = curr + curr (because prev now is equal to curr)

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

Comments

0

Because the second one does the operations at the same time meaning that for curr = curr + prev it uses your previous prev, not prev = curr

If you want a sequential assignment where the latter assignment depends on the previous, you should try the first method. The second method is WRONG!

Comments

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.