Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python เพื่อพิมพ์รูปแบบกระดานตรวจสอบของ n*n โดยใช้ numpy


ด้วยค่า 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