Reputation: 89
sumc=0
t = int(input())
while t :
x = input().split()
n = int(x[0])
k = int(x[1])
e = int(x[2])
m = int(x[3])
suma = [0]*(n-1)
Matrix = []
for i in range(n-1):
Matrix.append([])
for j in range(e):
p = int(input())
Matrix[i].append(p)
for i in range(n-1):
for j in range(e):
suma[i] = suma[i] + Matrix[i][j]
for j in range(e):
p = int(input())
Matrix[n-1][j].append(p)
suma.sort(suma,suma+(n-1))
for j in range(e-1):
sumc = sumc + Matrix[n-1][j]
for z in range(m+1):
if(suma[k-1] < sumc+z):
break
if (z==m+1):
print("imposible")
else:
arr[n-1][e-1] = z
print(arr[n-1][e-1])
t-=1
I want to access array by keeping one parameter/row/column (here row represented by (n-1), in line 21) constant. But getting error "index out of range". In general, how to access arrays for such type of problems where one of the parameters is/are constant.
Traceback (most recent call last):
File "C:/Users/User/untitled/cde_chf_entexam.py", line 21, in <module>
Matrix[n-1][j].append(p)
IndexError: list index out of range
Process finished with exit code 1
JUST SEE THE LINE 20-21 FOR THE ERROR, WHOLE CODE IS NOT NECESSARY, IT'S POSTED IF IT MIGHT HELP
Upvotes: 0
Views: 47
Reputation: 309929
Your loop:
for i in range(n-1):
Matrix.append([])
for j in range(e):
p = int(input())
Matrix[i].append(p)
adds n-1
elements to Matrix
. Since python is 0 indexed, this means that the highest index in Matrix
is n-2
.
When you do: Matrix[n-1][j].append(p)
, the expression Matrix[n-1]
will fail with an IndexError
because n-1
is one higher than the highest indexible location (n-2
).
As an aside, lists of lists are valid data structures for storing matrices in pure python, but there are 3rd party libraries dedicated to making matrices easier to work with. The de-facto standard in this area is numpy
.
Upvotes: 2