while循环中的增量列表索引

时间:2016-02-25 18:31:36

标签: python-2.7 fibonacci

我正在尝试打印Fibonacci中的前12个数字。我的想法是增加两个列表索引号。

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

请注意我是初学者,我试图在不使用内置函数的情况下执行此操作。 (我确定有某种斐波那契序列发生器)。

提前感谢您的帮助!

3 个答案:

答案 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 :(得分:1)

list = [0,1]

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

效率不高,但又快又脏。 使用&lt; 12因为在第11个循环中你将第12个条目添加到列表中。 使用list [x],您可以访问第一个条目从0开始的x条目。

编辑: 输出

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

答案 2 :(得分: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

同样要获得前12个数字,您可以将while循环条件设置为&lt; 12因为Python列表索引从0开始。