I want to test a 2x2 matrix of [[5,6],[7,8]] to see if it's a square.
I run my code and I'm supposed to get True but I got False instead...
def square(sq):
for element in sq:
if element:
return False
return True
I want to test a 2x2 matrix of [[5,6],[7,8]] to see if it's a square.
I run my code and I'm supposed to get True but I got False instead...
def square(sq):
for element in sq:
if element:
return False
return True
You pass a list of lists as a parameter. The example you gave is [[5,6],[7,8]].
Let's step to see what your code does with this input.
for element in sq:
if element:
return False
return True
Let's start with the for loop:
for element in sq:
This loops through your list, so the first iteration your element is [5,6] and the next [7,8].
The next thing that your code does is check if the element is True. A list is true if it's not empty. Therefore on the first iteration your code returns False.
An example input where your code would return True would be [[],[]].
To check if a matrix is square, you want to see if all the list dimensions are the same. Something along these lines:
def square(sq):
rows = len(sq)
for row in sq:
if len(row) != rows:
return False
return True