From where this 2 came in output? Fibonacci series using python Lists
From where this 2 came in output? Fibonacci series using python Lists
If you do not want to read this text, I have explained the problem in this Youtube video: https://youtu.be/Ekkkgjf0F_s
Following is the code that I am using to generate Fibonacci series using python
lists.
list1 = [0, 1]
x=1
while x <=2:
length = len(list1)
first =list1[length-2]
second =list1[length-1]
third = first + second
list1.append(third)
x+=1
print list1
When the while loop runs for the 1st iteration, it generates the upcoming element in series and stores in list exactly what it should do.
The list will now become:
list1 = [0,1,1]
But what confusing me is when the second iteration is made by while loop.
If you dry run the code, you will see that the code is outputting 2 (according to fibonacci series sequence, it is right)
but if we dry run the code, the 4th element should be 3 instead of 2
2nd interation, length = 3>>Dry RUN below:
3-2=1
3-1=2
1+2=3
list1 should be: [0,1,1,3]
But i am getting the output as:
list1=[0,1,1,2]
list1=[0,1,1,2]
I can't understand , how this 2 came in output.
2 Answers
2
your list has len()
of 3, and therefore your algorithm adds element 1 and 2 (which are both 1) together. that's why you get returned the 2.
len()
EDIT: which is exactly how the Fibonacci-Series goes....
Code with comments as follows:
length = len(list1) #3
first =list1[length-2] #list on index 1 is value 1
second =list1[length-1] #list on index 2 is value 1
third = first + second # 1+1 = 2
list1.append(third) # 2 is appended
x+=1
print list1
you probably confuse the value on list index [1] with the actual difference between len of list 3 and 1.
Oh my god. Thanks so much :)
– Ateeb
Aug 30 at 12:30
When you list1 becomes [0,1,1]
, the len of list1 is 3.
[0,1,1]
Now try running the following:
length = len(list1) = 3
first = list1[length-2] = list1[3-2] = list1[1] = 1
second = list1[length-1] = list1[3-1] = list1[2] = 1
third = first + second = 1 + 1 = 2
Hence, it adds 2 to the list.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Umm, the Fibonacci series goes as; 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
– ruohola
Aug 30 at 12:17