[题目整理]Write a code that inputs n and displays a n x n matrix with alternating diagonals of ones and

这篇博客介绍了如何用Python编写代码,根据输入的n生成一个n x n的矩阵,矩阵的主对角线和副对角线交替显示1和0。文章提供了两种实现方式,一种是直接修改0矩阵中的元素,另一种利用切片操作实现。还鼓励读者思考并实现另一种切片方式。最后,博主建议将功能封装为函数以提高代码的可读性和复用性。
摘要由CSDN通过智能技术生成

题目: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

**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值