[英]What is the problem about my fibonacci python code?
If you could look at my code.如果你能看看我的代码。
numbers = [1,2]
times = int(input("How many numbersM (minimum is 2)"))
def fibonacci(numbers, times):
for i in range(0, times):
for j in numbers:
numbers.append( numbers[j] + numbers[j+1])
print(numbers[i])
fibonacci(numbers, times)
If you run your code like that, you will get如果你像这样运行你的代码,你会得到
IndexError: list index out of range
because for j in numbers:
is a loop over the values in numbers
which contains value 1
which is an index out of range when you try to access numbers[j+1]
because there is no numbers[2]
at this point.因为
for j in numbers:
是对numbers
中的值进行循环,其中包含值1
,当您尝试访问numbers[j+1]
时,这是一个超出范围的索引,因为此时没有numbers[2]
。 Why do you need that second for
loop in there anyway?为什么你还需要第二个
for
循环呢? You will access the last and second-to-last values with numbers[i]
and numbers[i+1]
.您将使用
numbers[i]
和numbers[i+1]
访问最后一个和倒数第二个值。 No need to loop over the other values of your list.无需遍历列表的其他值。
I have removed that loop and if you run your code like this:我已经删除了那个循环,如果你像这样运行你的代码:
numbers = [1,2]
times = int(input("How many numbersM (minimum is 2)"))
def fibonacci(numbers, times):
for i in range(0, times):
numbers.append( numbers[i] + numbers[i+1])
print(numbers[i])
fibonacci(numbers, times)
You'll get something like this, for example:你会得到这样的东西,例如:
How many numbersM (minimum is 2)5
1
2
3
5
8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.