consider it as a distance from the center of the matrix with an offset.
[[int(max(abs((n-1)/2-i),abs((n-1)/2-j)))+1 for i in range(n)] for j in range(n)]
[[4, 4, 4, 4, 4, 4, 4],
[4, 3, 3, 3, 3, 3, 4],
[4, 3, 2, 2, 2, 3, 4],
[4, 3, 2, 1, 2, 3, 4],
[4, 3, 2, 2, 2, 3, 4],
[4, 3, 3, 3, 3, 3, 4],
[4, 4, 4, 4, 4, 4, 4]]
here n is an odd value, the center of the matrix is (n-1)/2. Since you want "1" at the center add one as offset, division converts the numbers to float format, so int() for nice formatting. List comprehension can be converted to nested loop but seems fine this way since eliminates the matrix initialization step.
The distance is called Chebyshev distance (or chessboard distance).
To covert the matrix into a String array, convert digits to corresponding chars and join the rows. At this point readability fails
[''.join([chr(ord('A')+int(max(abs((n-1)/2-i),abs((n-1)/2-j)))) for i in range(n)]) for j in range(n)]
['DDDDDDD', 'DCCCCCD', 'DCBBBCD', 'DCBABCD', 'DCBBBCD', 'DCCCCCD', 'DDDDDDD']
use functions!
def chebDist(i,j,n):
return int(max(abs((n-1)/2-i),abs((n-1)/2-j)))
def toChar(d):
return chr(ord('A')+d-1)
[''.join([toChar(chebDist(i,j,n)+1) for i in range(n)]) for j in range(n)]
will give you
['DDDDDDD', 'DCCCCCD', 'DCBBBCD', 'DCBABCD', 'DCBBBCD', 'DCCCCCD', 'DDDDDDD']
or perhaps this format
print('\n'.join([''.join([toChar(chebDist(i,j,n)+1) for i in range(n)]) for j in range(n)]))
DDDDDDD
DCCCCCD
DCBBBCD
DCBABCD
DCBBBCD
DCCCCCD
DDDDDDD
readable and with reusable functions!
You can perhaps make it more readable by separating the conversions, tradeoff is efficiency due to intermediate values
first create the numerical matrix
m=[[chebDist(i,j,n)+1 for i in range(n)] for j in range(n)]
convert to char mapping
c=[[toChar(e) for e in row] for row in m]
convert to String representation and print.
print('\n'.join([''.join(row) for row in c]))
UPDATE
Finally, all wrapped up into 4 generic functions and 2 lines of code.
def chebDist(i,j,n):
return int(max(abs((n-1)/2-i),abs((n-1)/2-j)))
def toChar(d):
return chr(ord('A')+d-1)
def map2(f,m):
return [[f(e) for e in row] for row in m]
def toString(a):
return '\n'.join(map(''.join,a))
m=[[chebDist(i,j,n)+1 for i in range(n)] for j in range(n)]
print(toString(map2(toChar,m)))