-
Notifications
You must be signed in to change notification settings - Fork 181
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Kalpak Take
authored
Nov 8, 2017
1 parent
063abf4
commit 2c11269
Showing
1 changed file
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
# from cs 101 course of udacity.com (problem set solved solution) | ||
|
||
# Given a list of lists representing a n * n matrix as input, | ||
# define a procedure that returns True if the input is an identity matrix | ||
# and False otherwise. | ||
|
||
# An IDENTITY matrix is a square matrix in which all the elements | ||
# on the principal/main diagonal are 1 and all the elements outside | ||
# the principal diagonal are 0. | ||
# (A square matrix is a matrix in which the number of rows | ||
# is equal to the number of columns) | ||
|
||
def is_identity_matrix(matrix): | ||
total_elems = 0 | ||
last_pos = 0 | ||
for row in matrix: | ||
total_elems += len(row) | ||
if row[last_pos] == 1 and row.count(0) == len(row) - 1: | ||
last_pos += 1 | ||
else: | ||
return False | ||
if total_elems == len(matrix[0]) * len(matrix[0]): | ||
return True | ||
else: | ||
return False | ||
|
||
|
||
# Test Cases: | ||
|
||
matrix1 = [[1,0,0,0], | ||
[0,1,0,0], | ||
[0,0,1,0], | ||
[0,0,0,1]] | ||
print is_identity_matrix(matrix1) | ||
#>>>True | ||
|
||
matrix2 = [[1,0,0], | ||
[0,1,0], | ||
[0,0,0]] | ||
|
||
print is_identity_matrix(matrix2) | ||
#>>>False | ||
|
||
matrix3 = [[2,0,0], | ||
[0,2,0], | ||
[0,0,2]] | ||
|
||
print is_identity_matrix(matrix3) | ||
#>>>False | ||
|
||
matrix4 = [[1,0,0,0], | ||
[0,1,1,0], | ||
[0,0,0,1]] | ||
|
||
print is_identity_matrix(matrix4) | ||
#>>>False | ||
|
||
matrix5 = [[1,0,0,0,0,0,0,0,0]] | ||
|
||
print is_identity_matrix(matrix5) | ||
#>>>False | ||
|
||
matrix6 = [[1,0,0,0], | ||
[0,1,0,1], | ||
[0,0,1,0], | ||
[0,0,0,1]] | ||
|
||
print is_identity_matrix(matrix6) | ||
#>>>False | ||
|
||
matrix7 = [[1, -1, 1], | ||
[0, 1, 0], | ||
[0, 0, 1]] | ||
print is_identity_matrix(matrix7) | ||
#>>>False | ||
|
||
|