Answer the question
In order to leave comments, you need to log in
Why IndexError when populating an array?
There is a matrix (list of lists).
It is necessary to change the numbers on the main diagonal: if the number is less than zero, then replace it with 0, otherwise with one.
Example:
Input:
[
[-1, 4, -5, -9, 3 ],
[ 6, -4, -7, 4, -5 ],
[ 3, 5, 0, -9, -1 ],
[ 1, 5, -7, -8, -9 ],
[-3, 2, 1, -5, 6 ]
]
[
[ 0, 4, -5, -9, 3 ],
[ 6, 0, -7, 4, -5 ],
[ 3, 5, 1, -9, -1 ],
[ 1, 5, -7, 0, -9 ],
[-3, 2, 1, -5, 1 ]
]
def res(m):
matrix = [[] for _ in range(len(m))] # новая пустая матрица
for i in range(len(m)):
for j in range(len(m[i])):
if i == j and m[i][j] < 0: # i - индекс списка в матрице, j - индекс элем. в конкретном сп.
matrix[i][j] = 0 # новый элемент, равный нулю. Здесь и вылетает исключение
elif i == j and m[i][j] >= 0:
matrix[i][j] = 1
else:
matrix[i][j] = m[i][j]
return matrix
print(res([
[-1, 4, -5, -9, 3],
[6, -4, -7, 4, -5],
[3, 5, 0, -9, -1],
[1, 5, -7, -8, -9],
[-3, 2, 1, -5, 6]
]))
matrix[i][j] = 0
IndexError: list assignment index out of range
Answer the question
In order to leave comments, you need to log in
This is not done in python, to add an element to a list, use the .append() method
if i == j and m[i][j] < 0: # i - индекс списка в матрице, j - индекс элем. в конкретном сп.
matrix[i].append(0)
elif i == j and m[i][j] >= 0:
matrix[i].append(1)
else:
matrix[i].append(m[i][j])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question