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.





Umm, the Fibonacci series goes as; 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
– ruohola
Aug 30 at 12:17





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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế