题目:Write a code that inputs n and displays a n x n matrix with alternating diagonals of ones and zeros. (python 实现)
做法1:
构建一个零矩阵,找出0和1的位置规律,并相应位置的0更改为1。
import numpy as np
n = int(input())
arr = np.zeros((n,n),dtype=int)
for i in range(n):
for j in range(n):
if ((i+1)%2 == 1):
if ((j+1)%2 ==0):
arr[i][j] =1
elif ((i+1)%2 == 0):
if ((j+1)%2 == 1):
arr[i][j] =1
print(arr)
测试效果如下:
有更简便的方法嘛?
参考自GeeksforGeeks,点此处跳转至原blog
介绍一种矩阵操作 slice(切片):
- arr[1::2,::2] = 1 : 从第一行开始,之后的行数为1+2, 1+2+2, 1+2+2+2…增加。列数从第0列开始(array的行列从0开始计数),之后的列数0+2,0+2+2,0+2+2+2… 这样就实现了间隔取1的效果。
- arr[::2,1::2] = 1 留给读者去考虑~
import numpy as np
n = int(input())
arr = np.zeros((n,n),dtype=int)
arr[1::2,::2] = 1
arr[::2,1::2] = 1
print(arr)
参考原网站的代码,将功能封装为一个函数,调用和维护更加方便
import numpy as np
def printcheckboard(n):
x = np.zeros((n,n), dtype = int)
x[1::2, ::2] = 1
x[::2. 1::2] = 1
for i in range(n):
for j on range(n):
print(x[i][j], end = '')
print()
n = int(input())
printcheckboard(n)
**
END
**