Home > front end >  Python matrix with increasing numbers
Python matrix with increasing numbers

Time:04-05

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. Maybe the explanation is a bit confusing, let me give an example:

The matrix, when the input is 3, 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 I continue. Any help or criticism of the code is welcome!

Thank you!

CodePudding user response:

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

CodePudding user response:

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! Its probably possible to tweak this a little bit more.

  • Related