2016-02-25 54 views
2

我試圖在斐波那契中打印前12個數字。我的想法是增加兩個列表索引號。在while循環中遞增列表索引

list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers 

listint = list[0] #sets the list variable I want to incremented 
list2int = list[1] #set the other list variable to be incremented 

while len(list) < 13:  #sets my loop to stop when it has 12 numbers in it 
    x = listint + list2int  #calculates number at index 2 
    list.append(x)  #appends new number to list 
    listint += 1 #here is where it is supposed to be incrementing the index 
    list2int +=1 
print list 

我的輸出是:

[0, 1, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21] 

我想:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 

請注意,我是初學者,我試圖做到這一點不使用內置的功能。 (我確定有某種斐波那契序列發生器)。

在此先感謝您的幫助!

+0

它是否工作進行到底? –

回答

0

變化while循環的第一行:

list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers 

listint = list[0] #sets the list variable I want to incremented 
list2int = list[1] #set the other list variable to be incremented 

while len(list) < 12:  #sets my loop to stop when it has 12 numbers in it 
    x = list[listint] + list[list2int]  #calculates number at index 2 
    list.append(x)  #appends new number to list 
    listint += 1 #here is where it is supposed to be incrementing the index 
    list2int +=1 
print list 

也得到1日12號因爲Python列表索引從0

1

問題出在while循環的最後兩行。您每次加1,而不是使用列表的是以前的斐波那契數的最後兩個元素:

list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers 

listint = list[0] #sets the list variable I want to incremented 
list2int = list[1] #set the other list variable to be incremented 

while len(list) < 13:  #sets my loop to stop when it has 12 numbers in it 
    x = listint + list2int  #calculates number at index 2 
    list.append(x)  #appends new number to list 
    listint = list[-2] #here is where it is supposed to be incrementing the index 
    list2int = list[-1] 
print list 
1
list = [0,1] 

while len(list) < 12: 
    list.append(list[len(list)-1]+list[len(list)-2]) 
print list 

不是很高性能的,但快速和骯髒的開始,您可以設置while循環條件< 12。 使用< 12因爲在第11個循環中,您將第12個條目添加到列表中。 使用列表[x],您可以訪問第一個條目從0開始的x的條目。

編輯: 輸出

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]