0

I am learning python in college, and have been having trouble with some concepts, mainly loops. I need help understanding why my code is producing an incorrect result:

def fibonacci(maxint):
    a, b = 0, 1
    LIST = [a, b]
    while b < maxint:
        a, b = b, a + b
        LIST.append(b)
    return LIST

In order to test the script, I need to call the function and pass 10 as an argument in the console:

>>>fibonacci(10)

The output should show as:

[0, 1, 1, 2, 3, 5, 8]

but it is actually printing:

[0, 1, 1, 2, 3, 5, 8, 13]

Can someone please analyze my code and tell me the following:

  1. where is it inefficient?
  2. Why is it going out of bounds and looping past 10 (the argument from my function)?
6
  • 2
    Because you test on b < maxint, then update b (which can go out of bounds) and finally append the updated one... Commented Mar 20, 2017 at 0:21
  • Furthermore what should happen if you call fibonacci(0). In that case I would expect an empty list? Commented Mar 20, 2017 at 0:24
  • What makes you think the code's inefficient? Commented Mar 20, 2017 at 0:28
  • What's a nested while loop? In your terminology, what would a non-nested while loop look like? Commented Mar 20, 2017 at 0:31
  • It is helpful to actually work through the logic of your while-loops with pencil and paper for small examples. It should become clear why it is always appending the first value past maxint Commented Mar 20, 2017 at 0:41

1 Answer 1

1

Firstly, Your code is not inefficient as it is an iterative approach for generating Fibonacci numbers.

Secondly, the following code will rectify the problem with your code regarding values appending beyond maxint :

def fibonacci(maxint):
    a, b = 0, 1
    LIST = [a]
    while b < maxint:
        LIST.append(b) # appending the b's value to the list before it is updated.
        a, b = b, a + b
    return LIST

Your code was printing '13' because you are appending the value of 'b' into the list after it's value is changed to '13'. So, in the last loop when value of 'b = 8', the new updated value will be 'b=13'.

>>>fibonacci(10)
>>>[0, 1, 1, 2, 3, 5, 8]
Sign up to request clarification or add additional context in comments.

1 Comment

What was the code's problem and why does this rectify it?

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.