使用 numpy 来打印 n*n 的棋盘格子模式的 Python 程序
给定 n 的值,我们的任务是为 n x n 矩阵显示棋盘格子模式。
numpy 中提供不同类型的函数来创建具有初始值的数组。NumPy是 Python 中用于科学计算的基础包。
算法
Step 1: input order of the matrix. Step 2: create n*n matrix using zeros((n, n), dtype=int). Step 3: fill with 1 the alternate rows and columns using the slicing technique. Step 4: print the matrix.
示例代码
import numpy as np
def checkboardpattern(n):
print("Checkerboard pattern:")
x = np.zeros((n, n), dtype = int)
x[1::2, ::2] = 1
x[::2, 1::2] = 1
# print the pattern
for i in range(n):
for j in range(n):
print(x[i][j], end =" ")
print()
# Driver code
n = int(input("Enter value of n ::>"))
checkboardpattern(n)
输出
Enter value of n ::>4 Checkerboard pattern: 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP