How can I make this loop works? - python

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)

Related

Indexing error scanning list

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.

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.

Using for loop to iterate two variables together

How do I go about doing something like this?
Say I have an array x = np.array([1,2,3,4,5]) of length 5,
for i,j in range(len(x)):
I want i and j to increment together.
This is throwing me an error message:
TypeError Traceback (most recent call last)
<ipython-input-4-37d0ddc3decf> in <module>()
----> 1 for i,j in range(len(x)):
2 print i,j
3
TypeError: only length-1 arrays can be converted to Python scalars
The reason I need this is because I have to use it in a condition inside the for loop. Like say, y[i][j] and I want this to be 0,0 then 1,1 and so on.
Why do you need j in the first place? If j is always equal to i, just use i. No need for a second variable.
Edited answer
OP says
The reason I need this is because I have to use it in a condition inside the for loop. Like say, y[i][j] and I want this to be 0,0 then 1,1 and so on.
In that case, you could simply use:
y[i][i]
Original answer
I'm not really sure why you would want to do that, you could just set it in the first line of the for loop:
for i in range(len(x)):
j = i
... #rest of the code follows
You could also use enumerate, as pointed in comments by #Julien, like below (but IMO, the earlier method is better):
>>> for i, j in enumerate(xrange(len(x))):
... print i, j
...
0 0
1 1
2 2
You could try this:
for i, j in zip(range(len(x)), range(len(x))):
print i, j
So the question is about how to iterate two variables, not why ;-)

Python numpy index is out of bound for axis zero

I have a code written in Python similar to the following:
def adamic_adar_prediction(graph):
adjacencyMatrix = graph.get_adjacency()
AAMatrix = adamic_adar_score(graph)
AAMatrix = np.array(AAMatrix)
i = (-AAMatrix ).argsort(axis=None, kind='mergesort')
j = np.unravel_index(i, AAMatrix .shape)
sortedList = np.vstack(j).T
print(sortedList.size)
print(sortedList[1658943])
print(sortedList[1658945])
While the result of the first print is 3,316,888 I receive the following error for the last print:
IndexError: index 1658944 is out of bounds for axis 0 with size 1658944
Any idea why this error arises for my array?
You don't have enough elements in your array, for example:
In [5]: import numpy as np
In [6]: a = np.array([1,2])
In [8]: a[2] # there is no element at 2nd index
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-8-016a87a854bc> in <module>()
----> 1 a[2]
IndexError: index 2 is out of bounds for axis 0 with size 2
Considering how mysterious your problem is, I'd go ahead and test this with a try/except loop to be sure the code goes past that point and is only having issues at index 1658944...
something like:
for x in range(sortedList.size):
try:
sortedList[x]
except:
print "no index at", x
Report back what your results are.
Thanks for all of the comments. I figured my problem is that sortedList.size returns total number of elements in the array while I was expecting the number of tuples in my array (since sortedList is a list of tuples [[],[],...]). So I solved my problem using sortedList.shape

Python error for loop

I am very new to programming and Python!
for i in range(0.6):
print(i)
I am getting error:
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
for i in range(0.6):
TypeError: 'float' object cannot be interpreted as an integer
Range takes in two values, not a single float!
It should be
for i in range(0,6):
print(i)
this would give you
0
1
2
3
4
5
or just range(6)
You probably meant this:
for i in range(0,6):
print(i)
You need to change period to comma. Also, you need to indent the print statement.
You probably mistyped, and meant to put a comma instead of a dot:
for n in range(0,6):
print(n)
actually, the '0' in range() is not even needed, you can also do this, and it will print the same thing:
for n in range(6):
print(n)
both would output:
0
1
2
3
4
5

Categories