Python 中的模式

Pattern in Python

我想在零点矩阵 80x80 中绘制菱形图案(使用 1)。上半场进行得非常好,但下半场我除了 0 什么也得不到。

img = np.zeros((80,80))

def draw_pic(image):
    for i in range(len(image)):
        for j in range(len(image[i])):
            print(int(image[i][j]), end = '')
        print()

def gen_diamond(image):
    ret = np.copy(image)
    for i in range(len(image)):
        for j in range(len(image[i])):
            if (i < len(image)/2 and j >= len(image[i])/2 - (i + 1) and j <= len(image[i])/2 + i):
                ret[i][j] = 1
            if (i > len(image)/2 and j >= len(image[i])/2 - (i + 1)and j <= len(image[i])/2 - i):
                ret[i][j] = 1


    return ret

draw_pic(gen_diamond(img))

您的错误在下半部分的范围检查中。让我们看看第 42 行的算法 ...

        if (i > len(image)/2 and
            j >= len(image[i])/2 - (i + 1) and
            j <= len(image[i])/2 - i):

代入正确的值,我们有:

        if (42 > 40 and
            j >= 40 - (42 + 1) and
            j <= 40 - 42):

最后一个条件不可能发生:您需要从中点减去行号并取绝对值。更简单的是,只需将循环值直接设置为您需要的范围即可:

row_mid = len(image) // 2
col_mid = len(image[0]) // 2

for row in range(row_mid):
    for col in range(col_mid-row, col_mid+row):
        print(row, col)
        ret[row, col] = 1

for tmp in range(row_mid):
    row = len(image) - tmp    # Work from the bottom up
    for col in range(col_mid-tmp, col_mid+tmp):
        ret[row, col] = 1 

10x10 数组的输出:

0000000000
0000110000
0001111000
0011111100
0111111110
0000000000
0111111110
0011111100
0001111000
0000110000

我相信你会调整边界条件。 :-)

这是一个解决方案。它适用于 even by even 和 odd x odd 图像网格。

img = np.zeros((12,12))


def draw_pic(image):
    for i in range(len(image)):
        for j in range(len(image[i])):
            print(int(image[i][j]), end = '')
        print()

def gen_diamond(image):
    ret = np.copy(image)
    for i in range(len(image)):
        for j in range(len(image[i])):
            if (i < len(image)/2 and j >= len(image[i])/2 - (i + 1) and j <= len(image[i])/2 + i):
                ret[i][j] = 1
            if (i >= len(image)/2 and j >= i-len(image[i])/2 and j <= (3/2*len(image[i])-i)-1):
                ret[i][j] = 1


    return ret

draw_pic(gen_diamond(img))

12x12 的输出看起来像这样

000001100000
000011110000
000111111000
001111111100
011111111110
111111111111
111111111111
011111111110
001111111100
000111111000
000011110000
000001100000

这是 11 x 11

00000100000
00001110000
00011111000
00111111100
01111111110
11111111111
01111111110
00111111100
00011111000
00001110000
00000100000