theeviininja
theeviininja

Reputation: 157

Function with nested WHILE loop producing unexpected results

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)?

Upvotes: 0

Views: 64

Answers (1)

Satish Prakash Garg
Satish Prakash Garg

Reputation: 2233

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]

Upvotes: 1

Related Questions