Skip to content Skip to sidebar Skip to footer

Trying To Understand Nested Loops, Identity Matrix

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

Solution 1:

First thing first, your indentation seems broken. You should always indent correctly especially in python. It should be:

defidentity(lst):for i in lst:for j in i:ifi==jandlst[i][j]==1:ifi!=jandlst[i][j]==0:returnTruereturnFalse

Secondly, you're not accessing the elements in the way you think you are. If I go ahead and print inside your loops with:

for i in lst:
    for j in i:
        print"i:", i, "j:", j
    print

I get:

i: [1, 0, 0] j:1i: [1, 0, 0] j:0i: [1, 0, 0] j:0i: [0, 1, 0] j:0i: [0, 1, 0] j:1i: [0, 1, 0] j:0i: [0, 0, 1] j:0i: [0, 0, 1] j:0i: [0, 0, 1] j:1

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

ifi==jandlst[i][j]==1:ifi!=jandlst[i][j]==0:# you never reach below here returnTrue# because i == j is always true in here# provided by the first conditional

You need to seperate those conditionals. Even if you do that you'll get the a wrong answer because it will return True even 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 False in conditionals (and ofc don't forget to change them respectively) and return True in the end if you don't find any errors.

Let me know how you progress, I can give you more hints..

Solution 2:

Since it's something you are going to use alot, you could just make it a class.

class Identity3(object):
  matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
  def __eq__(self, other):
    returnself.matrix == other
  def __new__(self):
    return[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
  def __init__(self):
    pass

Try using it like so,

>>> translate = [[1, 0, 0], [0, 1, 0], [1, 1, 1]]
>>> translate == Identity()
False
>>> idmatrix = Identity()
>>> idmatrix
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Solution 3:

Since you don't want the whole answer and only a hint: all elements on the diagonal should be 1; and the sum of all the elements in the matrix needs to be equal to the size of the diagonal.

Solution 4:

Just to be a bit more specific, don't forget to also check that if i != j, lst[i][j] == 0.

Post a Comment for "Trying To Understand Nested Loops, Identity Matrix"