I'm still something of a beginner with Python and I was trying to optimise a function to generate the Fibonacci sequence to a specified number of values. This is the code I have written:
def attempt2(length):
listy=[]
for i in range(0,length 1):
if i == 0:
listy.append(1)
elif i == 1:
listy.append(1)
else:
listy.append(listy[i] listy[i-1])
return listy
Whilst keeping this structure I have found no way to overcome the 'list index out of range' error. I think because the listy[i-1] would be out of range when i = 0, but if the function progresses through the loop linearly then the else statement should only take effect when i = 2. Can anyone see what I'm doing wrong?
Thanks!
CodePudding user response:
So, to find out the source of your issue, we need to take a step back to see what your loop is doing.
Initially, your for-loop is counting from 0 to whatever the length is, let's see what the values for i will look like:
0 1 2 ...
so starting from 2, since the behavior of 0,1 is defined:
listy.append(listy[2] listy[1])
Remember that listy has 2 items now, which are zero indexed, in other words the items are 1 and 0, hence the item listy[2] doesn't exist.
Thus, your code should be
listy.append(listy[i-2] listy[i-1])
CodePudding user response:
It's not a good solution overall but the tiny mistake is that you should change line 9 to:
listy.append(listy[i - 1] listy[i - 2])
Also you'll have a `length 1` size list not `length`.
CodePudding user response:
You are using wrong list indices
def attempt2(length):
listy=[]
for i in range(0,length):
if i == 0:
listy.append(1)
elif i == 1:
listy.append(1)
else:
listy.append(listy[i -1] listy[i - 2])
return listy
print(attempt2(12))
#[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
CodePudding user response:
Listy[-1] returns the last element of your list.
List position is initialising at 0 not 1.
When i = 2, in your else statement listy.append(listy[i] listy[i-1]) is equivalent to listy.append(listy[2] listy[1])
Yet, your list after the second loop is equal to [1,1].
The max pos is 1 and 2 is out of range.