Answer the question
In order to leave comments, you need to log in
How to understand matrices in Python?
Output an n×n table filled with numbers from 1 to n2 (square) in a spiral starting from the upper left corner and twisting clockwise, as shown in the example (here n=5):
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
On the second day I gave up and found a solution on the Internet, but I didn’t understand anything, here is the code itself:
n = int(input())
i, j = 0, -1
max_j, max_i = n - 1, n - 1
min_j, min_i = 0, 1
count = 1
mtrx = [[0 for j in range(n)] for i in range(n)]
while True:
while j < max_j:
j += 1
mtrx[i][j] = count
count += 1
max_j -= 1
while i < max_i:
i += 1
mtrx[i][j] = count
count += 1
max_i -= 1
while j > min_j:
j -= 1
mtrx[i][j] = count
count += 1
min_j += 1
while i > min_i:
i -= 1
mtrx[i][j] = count
count += 1
min_i += 1
if j == (n - 1) // 2 and i == n // 2:
break
print()
print()
for i in range(n):
for j in range(n):
print(mtrx[i][j], end = ' ')
print()
Answer the question
In order to leave comments, you need to log in
There are no matrices in python, there are matrices in mathematics
In python, for example, lists are used to work with them - as in your code
Here, a list is initialized that stores a matrix in itself - a list with nested lists inside
In special packages like Numpy and others, there may be more sharpened sub matrices and operations with them structures
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question