You can read description of the problem at: https://leetcode.com/problems/spiral-matrix
I was trying to solve this problem and I came up with the following code. But it fails due to IndexError: pop from empty list
error. Take a look at the code:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
answer = []
while matrix:
answer.append(matrix.pop(0))
for i in range(len(matrix)):
answer.append(matrix[i].pop())
#print(matrix)
answer.append(matrix.pop(-1))
for i in range(len(matrix))[::-1]:
answer.append(matrix[i].pop(0))
return answer
The program deletes the first row of the matrix, then deletes last elements of all rows, then it is supposed to delete the last row but this is where the error arises. To understand why this happens I tried to output matrix before this step (imagine that #print(matrix)
is now uncommented) So in the testcase where matrix = [[1,2,3],[4,5,6],[7,8,9]]
the output is [[4, 5], [7, 8]] []
These last 2 brackets seem to be causing the mistake. Where do they come from and how do I get rid of them?