abd
abd

Reputation: 155

How to create array from input range

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

Upvotes: 0

Views: 123

Answers (3)

yascho
yascho

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

Melvin Abraham
Melvin Abraham

Reputation: 3036

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.

Upvotes: 1

itismoej
itismoej

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

Related Questions