Python matrix with increasing numbers

Viewed 118

My problem here is that I need a 2 dimensional array, that holds the value 1 in the center of the matrix and then other numbers continue from that point. For example, when the input is 3, the matrix should look like this:

[[3, 3, 3, 3, 3],
[3, 2, 2, 2, 3],
[3, 2, 1, 2, 3],
[3, 2, 2, 2, 3],
[3, 3, 3, 3, 3]]

This is my code so far:

import pprint

def func(number):
    d = [[0] for i in range(number + (number - 1))]
    #? Create the matrix with 0 value inside each index and determine the amount of columns

    for i in d:
        d[d.index(i)] = [number] * (number + (number - 1))
        #? Add values to the indexes
        #?              [value inside] * [length of a row]


    centre = len(d) // 2
    #? centre is the index value of the list which contains the number 1
    
    pprint.pprint(d)

func(3)

The result is this:

[[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3]]

My approach was to fill the whole table with the number given, then work with the rest of the table without the first and last array, because they won't change and their value will always be the number times amount necessary.

I even know at what index of the 2D array the center is. However, I am stuck here. I'm not sure how to continue from here.

2 Answers

The value at each index is given by the maximum of (distance from the row index to the center, distance from the column index to the center). So, you can do:

n = 3
dim = 2 * n - 1

result = [
    [
        max(abs(row - dim // 2), abs(col - dim // 2)) + 1
        for col in range(dim)
    ]
    for row in range(dim)
]

print(result)

This outputs:

[[3, 3, 3, 3, 3],
[3, 2, 2, 2, 3],
[3, 2, 1, 2, 3],
[3, 2, 2, 2, 3],
[3, 3, 3, 3, 3]]

Fun question!

Here's what I came up with. It's quite shorter than your implementation:

import numpy as np
mdim = (5, 5) # specify your matrix dimensions
value = 3 # specify the outer value
matrix = np.zeros(mdim) # initiate the matrix
for i, v in enumerate(range(value, 0, -1)):  # let's fill it!
    matrix[i:(mdim[0]-i), i:(mdim[1]-i)] = v
print(matrix)

The output is as desired! It's probably possible to tweak this a little bit more.

Explanations: It first creates a matrix of zeros with the dimensions of mdim. Then, it fills the matrix with the values of v=3 from rows 0:5 and columns 0:5. It successively fills the matrix with the values of v-1=2 from rows 1:4 and columns 1:4, until the centre gets the final value of 1.

Related