In: Computer Science
Write a python function (Without using external libraries) to calculate the 1). determinate of a 2 x 2 matrix 2). Calculate the inverse of a 2 x 2 matrix.
matrix1=[]
for i in range(0,2): # Loops for rows
element =[] # Creating an empty list for each row
for j in range(0,2): # Loops for columns
element.append(int(input())) # Takes input from user and appends to matrix1
matrix1.append(element) # Appending the scanned element to matrix indexes
Determinant=matrix1[0][0]*matrix1[1][1] - matrix1[0][1]*matrix1[1][0] # Finding the determinant
print("Determinant is {}".format(Determinant)) # Prints the determinant
matrix_inv=[[],[]] # Creates the empty list of list for rows and columns
store=1/Determinant # Stores the inverse of determinant
if(Determinant==0):
print("Inverse doesnot exist")
else:
matrix_inv[0].append(matrix1[1][1]*store) # Does inverse operation for the 1x1 positions
matrix_inv[0].append(-(matrix1[0][1]*store))# Does inverse operation for the 0x1 positions
matrix_inv[1].append(-(matrix1[1][0]*store))# Does inverse operation for the 1x0 positions
matrix_inv[1].append(matrix1[0][0]*store) # Does inverse operation for the 0x0 positions
print("Inverse of a matrix is {}".format(matrix_inv)) # Prints the inverse of matrix