gpt4 book ai didi

python - Python 中的模式

转载 作者:太空宇宙 更新时间:2023-11-03 21:34:19 24 4
gpt4 key购买 nike

我想在 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

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

关于python - Python 中的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53329841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com