Reputation: 155
1
then out is [ [1] ]
2
then out is [ [1,2],[3,4] ]
2x2 array3
then out is [ [1,2,3],[4,5,6],[7,8,9] ]
3x3 arraywith respect to number the value will be keep on increasing
# A is input
A = 3
matrix = [[0]*A for i in range(A)]
# matrix = []
for i in range(A):
for j in range(A):
matrix.append(matrix[i][j])
matrix
I tried with below code
matrix = [[i+1 for i in range(3)] for i in range(3)]
matrix
I am getting [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Upvotes: 0
Views: 123
Reputation: 314
Splitting n^2 numbers into n bins:
np.split(np.arange(n**2)+1, n)
In detail:
import numpy as np
for n in range(1,4):
print(np.split(np.arange(n**2)+1, n))
Output:
[array([1])]
[array([1, 2]), array([3, 4])]
[array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]
Upvotes: 1
Reputation: 3036
The code is almost correct except the line matrix.append(matrix[i][j])
. Let's dig a bit...
Consider the line
matrix = [[0]*A for i in range(A)]
Here a new matrix of the shape A x A
is created which is what's expected in the final answer.
Then we have the two for loops which are iterating through each row and each column.
for i in range(A): # Iterating through each rows
for j in range(A): # Iterating through each columns
...
Now, let's look at the erroneous line
matrix.append(matrix[i][j])
This line adds new values at the end of a perfectly fine matrix which distorts the final shape of the matrix.
What you instead need to do is assign values in the corresponding row and column. Effectively, something like this:
matrix[i][j] = ...
Now, on the right hand side of the above expression goes (i * A) + (j + 1)
. So you can rewrite your program as follows:
A = 3
# Initialize the matrix
matrix = [[0]*A for i in range(A)]
for i in range(A):
for j in range(A):
# Replace the value at the corresponding row and column
matrix[i][j] = (i * A) + (j + 1)
print(matrix)
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
This is a pure Python solution, thus, it does not require any external library.
Upvotes: 1
Reputation: 1847
If you don't want to use numpy
, you can use list comprehension:
In [1]: a = 3
In [2]: [[j for j in range(((i-1)*a)+1, (a*i)+1)] for i in range(1, a+1)]
Out[2]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Upvotes: 1