Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

주어진 두 행렬이 동일한지 확인하는 Python 프로그램

<시간/>

여기에 두 개의 행렬이 제공됩니다. 두 행렬의 차수는 같습니다. 동일하게 두 행렬이 같아야 하려면 두 행렬의 행과 열 수가 같아야 하고 해당 요소도 같아야 합니다.

알고리즘

Step 1: Create two matrix.
Step 2: Then traverse every element of the first matrix and second matrix and compare every element of the first matrix with the second matrix.
Step 3: If the both are same then both matrices are identical.

예시 코드

# Program to check if two
# given matrices are identical
N=4
# This function returns 1
# if A[][] and B[][] are identical
# otherwise returns 0
def areSame(A,B):

   for i in range(n):
      for j in range(n):
         if (A[i][j] != B[i][j]):
            return 0
   return 1
 
# driver code
A=[]
n=int(input("Enter n for n x n matrix : "))    #3 here
#use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
print("Enter the element ::>")
for i in range(n): 
   row = []                                      #temporary list to store the row
   for j in range(n): 
      row.append(int(input()))                   #add the input to row list
   A.append(row)                                 #add the row to the list

print(A)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
   for j in range(n):
      print(A[i][j], end=" ")
   print()

B=[]
n=int(input("Enter N for N x N matrix : "))    #3 here
#use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
print("Enter the element ::>")
for i in range(n): 
   row = []                                      #temporary list to store the row
   for j in range(n): 
      row.append(int(input()))                   #add the input to row list
   B.append(row)                                 #add the row to the list

print(B)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
   for j in range(n):
      print(B[i][j], end=" ")
   print()

if (areSame(A, B)==1):
   print("Matrices are identical")
else:
   print("Matrices are not identical")
 
# This code is contributed
# by Anant Agarwal.

출력

Enter n for n x n matrix : 2
Enter the element ::>
1
1
2
2
[[1, 1], [2, 2]]
Display Array In Matrix Form
1 1 
2 2 
Enter N for N x N matrix : 2
Enter the element ::>
1
1
2
2
[[1, 1], [2, 2]]
Display Array In Matrix Form
1 1 
2 2 
Matrices are identical