Reputation: 171
How can I add padding consisting of zeros to a 2D array (without using any additional modules)?
For example, I have the following grid:
1 0 1 1
0 1 1 0
1 0 0 1
1 0 1 1
I would like the output to be:
0 0 0 0 0 0
0 1 0 1 1 0
0 0 1 1 0 0
0 1 0 0 1 0
0 1 0 1 1 0
0 0 0 0 0 0
I have tried the following code and its working, but I would like to know if there is a better way to achieve this.
def padded_grid(grid):
gridpadding = []
extrarow = [0] * (len(grid) + 2)
gridpadding.append(extrarow)
for row in grid:
row.insert(0, 0)
row.append(0)
gridpadding.append(row)
gridpadding.append(extrarow)
return gridpadding
Upvotes: 1
Views: 885
Reputation: 3503
Read question wrong, so you want to set how much padding you want yet I implemented padding single layer. Simply padding multiple iterations would be simplest.
from pprint import pprint
source = [list(range(n, n + 4)) for n in range(4)]
pprint(source, width=41)
def pad_frame_once(src_: list, pad) -> list:
output = [[pad, *line, pad] for line in src_]
return [[pad] * len(output[0]), *output, [pad] * len(output[0])]
def pad_grid(src_, padding_size: int, pad=0):
reference = src_
for _ in range(padding_size):
reference = pad_frame_once(reference, pad)
return reference
pprint(pad_frame_once(source, pad=0))
pprint(pad_grid(source, 3))
[[0, 1, 2, 3],
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]]
[[0, 0, 0, 0, 0, 0],
[0, 0, 1, 2, 3, 0],
[0, 1, 2, 3, 4, 0],
[0, 2, 3, 4, 5, 0],
[0, 3, 4, 5, 6, 0],
[0, 0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 2, 3, 0, 0, 0],
[0, 0, 0, 1, 2, 3, 4, 0, 0, 0],
[0, 0, 0, 2, 3, 4, 5, 0, 0, 0],
[0, 0, 0, 3, 4, 5, 6, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
Process finished with exit code 0
Upvotes: 2
Reputation: 16683
Without any other libraries, you could use the following assuming a 2-d array called l
:
l = [[1, 0, 1, 1],
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 1, 1]]
def padded_grid(grid):
n = len(grid[0])
x = [0 for _ in range(n + 2)]
[lst.append(0) for lst in grid]
[lst.insert(0, 0) for lst in grid]
grid.insert(0,x)
grid.append(x)
return grid
padded_grid(grid=l)
[[0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 0],
[0, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0]]
Upvotes: 1