Answer to Question #190380 in Python for Arbab Abdul basit

Question #190380

Write a function called is_identity that takes a 2D list(matrix) of 3x3 as a parameter and return true or false if the matrix is identity matrix or notasquare matrix in which all the elements of the principal diagonal are ones and all other elements are zeros.


1
Expert's answer
2021-05-08T07:25:48-0400
def is_identity(matrix):
	'''
	function returns true if the matrix is identity matrix or
	notasquare matrix in which all the elements of the principal diagonal
	are ones and all other elements are zeros
	'''
	if len(matrix) == 0:
		return False
	identity = True
	for row in matrix:
		for el in row:
			if el != 1:
				identity = False
	if identity:
		return True
	if matrix[0] and len(matrix) == len(matrix[0]):
		return False
	diagonal_ones = True
	for i in range(len(matrix)):
		for j in range(len(matrix[i])):
			if i == j:
				if matrix[i][j] != 1:
					diagonal_ones = False
			else:
				if matrix[i][j] != 0:
					diagonal_ones = False
	if diagonal_ones:
		return True
	return False

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS