0
  • If input is 1 then out is [ [1] ]
  • If input is 2 then out is [ [1,2],[3,4] ] 2x2 array
  • if input is 3 then out is [ [1,2,3],[4,5,6],[7,8,9] ] 3x3 array

with 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]]

2

3 Answers 3

1

The code is almost correct except the line matrix.append(matrix[i][j]). Let's dig a bit...

  1. 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.

  2. 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
            ...
    
  3. 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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]]

Comments

1

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])]

3 Comments

can we do it in python native method
Sure, please see other answers. This solution is shorter though.
Additionally, this solution better reads what you actually want: to split n^2 numbers into n bins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.