Indexing error scanning list - python

I apologize ahead of time for the basic nature of this question but I could really use a different set of eyes to see why I'm still getting an IndexError: list index out of range.
Here is my code:
def longestRun(L):
counter=1
ii=0
counts=[1]
while ii<=max(range((len(L)))):
if L[ii] <= L[(ii+1)]:
counter+=1
ii+=1
else:
ii+=1
counts.append(counter)
counter=1
continue
counts.sort()
return counts[-1]
It is supposed to count the longest streak of consecutive increases for a list of integers. I got it working by subtracting 1 from the while statement but then it will not always show the right answer because it won't go through the whole list.
Here is my specific error message:
IndexError
Traceback (most recent call last)
<ipython-input-76-1b4664f2fb31> in <module>()
----> 1 longestRun(L)
C:\Users\james_000\Desktop\longestRun.py in longestRun(L)
4 counts=[1]
5 while ii<=max(range((len(L)))):
----> 6 if L[ii] <= L[(ii+1)]:
7 counter+=1
8 ii+=1

Your while loop is while ii<=max(range((len(L)))): and then your if statement's condition accesses L[ii+1] which runs off the end of the array.

It's simple math. Let's say L is of length 10. That makes the last index 9. ii can eventually be 9, thus ii+1 is going to be out of range.

Related

How can I make this loop works?

I feel dum cuz I was trying to make a simple loop for a matrix to show differents solves and I couldn't fix the index of the array: (FOA I am using the Jupyter Notebook with SageMath 9.3)
A=random_matrix(ZZ,4,4)
k=srange(2,7)
show(k)
i=0
for i in k:
show(A^k[i])
show(k[i])
And I receive that:
[2,3,4,5,6]
"The matrix"
4
"The matrix"
5
"The matrix"
6
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-7-c50cd3e70a78> in <module>
4 i=Integer(0)
5 for i in k:
----> 6 show(A**k[i])
7 show(k[i])
IndexError: list index out of range
How can I print in the right order the k esponent 2,3,4,5,6?
If you add a show(i) call, you'll see the value of i each time is:
2
3
4
5
6
So k[i] is getting the third element of k, then the fourth, etc. That's what you're seeing when you show(k[i]). There's only five elements in the list, so when i=5, you'll get an IndexError as you've seen.
Instead, just use i:
A=random_matrix(ZZ,4,4)
k=srange(2,7)
show(k)
i=0
for i in k:
show(A**i)
show(i)

I have an error " list index out of range" that I can't solve

I am working on a problem from code wars. It is "Delete occurrences of an element if it occurs more than n times".
The instructions are Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering.
For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].
Example: delete_nth ([1,1,1,1],2) # return [1,1] delete_nth ([20,37,20,21],1) # return [20,37,21]
The issue is that when I run this in code wars it comes back with the error.
Traceback (most recent call last):
File "tests.py", line 30, in <module>
do_test()
File "tests.py", line 9, in do_test
test.assert_equals(delete_nth([], 5), [], "From list [],5 you get")
File "/workspace/default/solution.py", line 6, in delete_nth
if o.count(o[x]) > max_e:
IndexError: list index out of range
But everything is fine and I get zero errors when I run it in VSC. I know what the error is telling me but I just can't understand or see how that is.
def delete_nth(order,max_e):
o = order[::-1]
x = 0
while x != len(o)+1:
if o.count(o[x]) > max_e:
o.remove(o[x])
x += 1
if x >= len(o):
return(o[::-1])
return(o[::-1])
Try putting
if order == []:
return []
before the while loop (of course at the same indentation level with while).
The error happens when you put [] as the first parameter, as the error message indicates. In that chase o in your code is an empty list, so in the while loop o[x] cannot be evaluated. The if above will deal with this pathological case.

How does this code not get an index error when the loop variable gets to the end of the range in a for loop?

This was a HW problem in edX that asked me to determine how many times the word "bob" occurred within some string. I got to a solution, but I'm confused as to why it works. For code(1):
CODE(1)
s = 'azcbobobegghakl'
count = 0
for i in range(len(s)):
if s[i:i+3] == "bob":
count += 1
print(count)
In the same HW, there was a problem that asked me to find the longest sub-string in alphabetical order within some string. In the beginning of finding the solution, I was faced with an index error because I was trying to refer to an index that was out of range; shown in this code:
CODE(2)
s = 'azcbobobegghakl'
temp = ''
longest = ''
for i in range(len(s)):
if s[i] <= s[i+1]:
temp += s[i+1]
if len(temp) > len(longest):
longest = temp
else:
temp = s[i+1]
print(longest)
ERROR(2)
Traceback (most recent call last):
File "C:/Users/vchi/PycharmProjects/edX/introduction.py", line 5, in <module>
if s[i] <= s[i+1]:
IndexError: string index out of range
Why is it that CODE(1) is not faced with the the same kind of error that CODE(2) received when i > len(s)-4 and s[i:i+3] tries to refer to things that are out of bounds? Thank you in advance!
Python slicing is weird in a lot of ways, and this is one that kind of proves this.
With strings in python if the slice goes out of range, it will just set the "end" of the slice as the last viable index so if we did something like:
a = 'boboabcdef'
and then did:
b = a[4:12]
we would just get b is equal to 'abcdef', as it would just disregard the rest of the string.
But when it comes to indexes for lists, python has a much stricter interpretation, as it would be incredibly difficult to debug a program where a list could go out of index with no errors or warnings.

List Index Error in Python

In this program, I want to search for a Number from a list. When I search a number that is in the list, it works correctly.
But if I search a number that it is not in list, it gives me this Error:
Traceback (most recent call last):
File "fourth.py", line 12, in <module>
if(AranaElemean==liste[i]):
IndexError: list index out of range
liste=[12,23,3489,15,345,23,9,234,84];
Number=11;
i=0;
Index=0;
isWhileActive=0;
while (i<len(liste) and Number!=liste[i]):
i=i+1;
if(Number==liste[i]):
Index=i;
isWhileActive=1;
else:
Index=0;
if(isWhileActive==0 and i!=0):
print("Please Enter Valid Number.");
else:
print("Index:",Index);
That's because i goes from 0 to len(liste) and inside the while loop you are increasing the i by one. So when it doesn't find the desired number and i gets the value i = len(liste), you increae it by 1 in the loop so you get the error because it exceeds the range of the list.
you can use the following
while (i<len(liste)):
if(Number==liste[i]):
Index=i;
isWhileActive=1;
break
else:
Index=0;
i += 1
Your condition should be:
while (i<len(liste)-1 and Number!=liste[i])
This is because Python list indexing begins at 0.
Therefore, for a list of length n you need to index from 0 to n-1.

Nested list sorting in Python

This is a question of nested loop where I have to find the names of students in alphabetical order with 2nd lowest marks.
I am getting following error:
Traceback (most recent call last):
File "solution.py", line 12, in <module>
if (l[i][0]==l[0][0]):
IndexError: list index out of range
Following is my complete code.
l=list()
p=list()
q=list()
for i in range (int(raw_input())):
p=[raw_input(),int(raw_input())]
p.reverse()
l.append(p)
l.sort()
print len(l)
for i in range(0,len(l)):
print "i= ",i
if (l[i][0]==l[0][0]):
l.remove(l[i])
print l
for i in range(0,len(l)):
if (l[i][0]==l[0][0]):
q.append(l[i][1])
q.sort()
for i in range(0,len(q)):
print q[i]
I have even printed the index which shows the values are in range. Please run the function to find the following output:
4
i= 0
i= 1
i= 2
i= 3
I will happy if I get any better method from my the community ,But my main concern is the error I am getting "Index Out of Range" .It doesn't seem right here
The problem is that you are removing items from a loop. The thumb rule is that you shall never remove items from a list while iterating over it.
I don't really understand your code right now, but you can just change the way you are doing the first loop and apply the same logic for the next ones, at least you will have what you want.
The idea here is that with the while statement, after each iteration, you will have another verification of the size of the list. Meanwhile with the for loop, only at the first time, since range will return a list and the for loop will just iterate over the list which was already created.
l=list()
p=list()
q=list()
for i in range (int(raw_input())):
p=[raw_input(),int(raw_input())]
p.reverse()
l.append(p)
l.sort()
print len(l)
i = 0
while i < len(l):
print "i= ",i
if (l[i][0]==l[0][0]):
l.remove(l[i])
i += 1
print l
You are using remove, because of that l, in some moment, have less elements than you expect.

Categories