使用 numpy 列印棋盤圖案的 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 a 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  

更新於: 2019 年 7 月 30 日

504 次瀏覽

開啟您的職業生涯

完成課程認證

入門
廣告
© . All rights reserved.