Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

python - How to create a 2D binary array with 1's forming a "diamond" shape

I need to create a function that results in a diamond shape when given a side length. The diamond array should consist of values of 0 and 1.

So far I figured out how to make the diamond, I don't know how to program a function for different side lengths

So far I have this solution for a side length of 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))

How could I write a function for different lengths?
Also, if given a length of 1 it should return [[1]]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using an intersection of horizontal and vertical patterns:

import numpy as np

N       = 5
H       = abs(np.arange(1-N,N+1,2))//2
V       = H[0] - 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]]

Visually, this corresponds to intersecting number equalities between rows and columns:

for 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  .  .  .

for 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  .  .  .         

If you want the diamond to be filled, use diamond = (H<=V)*1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...