So I am stuck on nested loops, I feel like I understand them about half the time and then I start to work on a different problem and then I don’t understand them anymore. Maybe I am over complicating things. Anyways back to my problem, I have an identity matrix
lst = [[1,0,0], [0,1,0], [0,0,1]]
I am trying to write a program that will check to see if it is an identity matrix, so I know that the index where i and j are have the same index(i.e i at position 0 and j at position 0; i at position 1 and j at position 1; i at position 2 and j at position 2) and are equal to 1 then the matrix is the identity matrix. Now my problem is I feel like I struggle articulating this to a computer. Or in other words lst[0][0], lst[1][1] and lst[2][2] should all equal 1 and all the other values should equal zero. Without giving me the answer can someone maybe nudge me in the right direction? I’ve been trying to solve this for about 2 weeks now I get am getting frustrated that I can’t since it seems so simple…
Thanks.
def identity(lst):
for i in lst:
for j in i:
if i == j and lst[i][j] == 1:
if i != j and lst[i][j] == 0:
return True
return False
I am getting false where am I going wrong?
I think I got it!!
def identity(lst):
size = len(lst)
for i in range(len(lst)):
if len(lst[i]) != size:
return False
for j in range(len(lst)):
if i == j and lst[i][j] != 1:
return False
elif i != j and lst[i][j] != 0:
return False
return True
Printing the i’s and j:
for i in range(len(lst)):
for j in range(len(lst)):
print("i:", i, "j:", j)
resulted in:
i: 0 j: 0
i: 0 j: 1
i: 0 j: 2
i: 1 j: 0
i: 1 j: 1
i: 1 j: 2
i: 2 j: 0
i: 2 j: 1
i: 2 j: 2
This really helped me a lot!
First thing first, your indentation seems broken. You should always indent correctly especially in python. It should be:
Secondly, you’re not accessing the elements in the way you think you are. If I go ahead and print inside your loops with:
I get:
You can use a combination of range (or xrange) and len functions if you need to iterate indices of the matrix.
Lastly your conditionals doesn’t make sense this way
You need to seperate those conditionals. Even if you do that you’ll get the a wrong answer because it will
return Trueeven if only one element satisfies the condition (i.e only one element is in the right place). I believe you need to think in the reverse way,return Falsein conditionals (and ofc don’t forget to change them respectively) andreturn Truein the end if you don’t find any errors.Let me know how you progress, I can give you more hints..