如何制作具有指定周长的正方形并添加边距?

How can I make a square with a specified circumference and add margin?

我正在尝试制作指定长度的方形路径:

我做了一个函数 - 如果我输入 20,那么我得到一个 6x6 矩阵。

如何添加 0 的边距,例如。 3 字段厚度?

像这样

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 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 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
def square(length): return [
    [1 for _ in range(length//4+1)]
    for _ in range(length//4+1)
]

for x in square(24):
    print(x)

这是一种方法。这里的一个警告是,由于我复制零行的方式,它们都是相同的列表。如果您修改了零行之一,它将修改所有零行。

def square(length): 
    zeros = [0]*(length//4+7)
    sq = [zeros] * 3
    sq.extend( [
        ([0,0,0] + [1 for _ in range(length//4+1)] + [0,0,0] )
        for _ in range(length//4+1)
    ])
    sq.extend( [zeros]*3 )
    return sq

for x in square(24):
    print(x)

这是一个 numpy 方法。

import numpy as np
def square(length): 
    c = length//4+1
    sq = np.zeros((c+6,c+6)).astype(int)
    sq[3:c+3,3:c+3] = np.ones((c,c))
    return sq

print( square(24) )

一种方法是将其构建为扁平字符串,然后使用 textwrap 将输出样式设置为正确的行数:

import textwrap

# The number of 1's in a row/column
count = 6
# The number of 0's to pad with
margin = 3
# The total 'size' of a row/column
size = margin + count + margin

pad_rows = "0" * size * margin
core = (("0" * margin) + ("1" * count) + ("0" * margin)) * count
print('\n'.join(textwrap.wrap(pad_rows + core + pad_rows, size)))

您可以准备一个 0 和 1 的线型,然后通过相交构建一个二维矩阵。

def square(size,margin=3):
    p = [0]*margin + [1]*(size-2*margin) + [0]*margin
    return [[r*c for r in p] for c in p]

for row in square(20):print(*row)

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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 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 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0