如何使用数组创建菱形函数

2024-04-27 23:37:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个函数,在给定边长的情况下得到菱形。菱形应该由0和1的数组组成

到目前为止,我知道了如何制作钻石,我不知道如何为不同的边长编写一个函数

到目前为止,我已经: 边长为3

import numpy as np

#line1
a=np.zeros(3+2)
a[3-1]=1

#line2
b=np.zeros(3+2)
b[3-2]=1
b[3]=1

#line3
c=np.zeros(3+2)
c[3-3]=1
c[3+1]=1

print(np.concatenate((a,b,c,b,a),axis=1).reshape(5,5))

如何为不同的长度编写函数 同样,如果给定长度1,它应该返回[[1]]

任何反馈都将不胜感激

更新:我认为一个循环可以计算出行数


Tags: 函数importnumpyasnpzeros情况数组
2条回答

我用了更长的方法,这样我就可以扩展函数来处理其他几何图形

import numpy as np

def diamondarray(dimension=1):

    #// initialize 2d array
    a=np.zeros((dimension,dimension))

    #// find the middle of the array
    midpoint=(dimension-1)/2

    #// initialize an offset
    offset=-1
    offsetstep=1

    #// loop through rows and columns
    for row in range(dimension):
        if dimension%2 == 0 and row == np.ceil(midpoint):
            #// repeat offset for second midpoint row
            offset=offset
        else:
            if row <= np.ceil(midpoint):
                #// increase offset for each row for top
                offset=offset+offsetstep
            else:
                #// decrease offset for each row for bottom
                offset=offset-offsetstep

        for col in range(dimension):
            #// set value to one
            if dimension%2 == 0:
                if col <= np.floor(midpoint):
                    if col == np.floor(midpoint)-offset:
                        a[row,col]=fill
                if col >= np.ceil(midpoint):
                    if col == int(midpoint)+offset+1:
                        a[row,col]=fill
            else:
                if col == midpoint+offset or col == midpoint-offset:
                    pass
                    a[row,col]=fill
    return a

对于N=5:

打印(diamondarray(5))

[[0. 0. 1. 0. 0.]
 [0. 1. 0. 1. 0.]
 [1. 0. 0. 0. 1.]
 [0. 1. 0. 1. 0.]
 [0. 0. 1. 0. 0.]]

对于N=8:

打印(diamondarray(8))

[[0. 0. 0. 1. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0. 1. 0. 0.]
 [0. 1. 0. 0. 0. 0. 1. 0.]
 [1. 0. 0. 0. 0. 0. 0. 1.]
 [1. 0. 0. 0. 0. 0. 0. 1.]
 [0. 1. 0. 0. 0. 0. 1. 0.]
 [0. 0. 1. 0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 1. 0. 0. 0.]]

可以使用水平和垂直图案的交点来执行此操作:

import numpy as np

N       = 5
H       = abs(np.arange(1-N,N+1,2))//2
V       = (N-1)//2-H[:,None]
diamond = (H==V)*1

print(diamond)

[[0 0 1 0 0]
 [0 1 0 1 0]
 [1 0 0 0 1]
 [0 1 0 1 0]
 [0 0 1 0 0]]

从视觉上看,这与行和列之间的相交数字相等相对应:

对于N=7:

     [3, 2, 1, 0, 1, 2, 3]
   0  .  .  .  x  .  .  .         
   1  .  .  x  .  x  .  .
   2  .  x  .  .  .  x  .     
   3  x  .  .  .  .  .  x
   2  .  x  .  .  .  x  .
   1  .  .  x  .  x  .  .
   0  .  .  .  x  .  .  .

对于N=8:

     [3, 2, 1, 0, 0, 1, 2, 3]
   0  .  .  .  x  x  .  .  .         
   1  .  .  x  .  .  x  .  .         
   2  .  x  .  .  .  .  x  .         
   3  x  .  .  .  .  .  .  x         
   3  x  .  .  .  .  .  .  x         
   2  .  x  .  .  .  .  x  .         
   1  .  .  x  .  .  x  .  .         
   0  .  .  .  x  x  .  .  .         

如果要填充菱形,请使用diamond = (H<=V)*1

相关问题 更多 >