Reputation: 7
I need to find how to check if the input, which is a list, is 2D with the same amount of columns as rows and the same amount of parts in them. Example: [[4,5],[4,5,6]] and [[2,3],[6,1],[2,9]]
would generate error messages. But [[3,4,5],[4,6,8],[5,8,-1]] and [[4,5],[4,1]]
would be correct.
I have tried:
for row in square:
if len(row) != len(square):
return False
but that doesn't work quite right.
EDIT: Also this check is at the start of a list of checks, so it need to be in a if statement format.
Upvotes: 0
Views: 1395
Reputation: 396
Is there a return value if the test is not failed? Putting your code in a function, assuming there's nothing more to the test:
def matrix_test(square):
for row in square:
if len(row) != len(square):
return False
...either returns False or doesn't return a value returns None. So if you test a matrix by calling this function, you will never get a True result for the matrices that pass the test. So if it's not already there, add the final line:
return True
You can then check a particular matrix with
if matrix_test(matrix001):
#run the next test
If that's not the problem it would help to see more of the code, and to know what happens when it runs.
Upvotes: 1
Reputation: 309851
Assuming your matrix is a sequence that holds other sequences (like a list of lists as you have in your question), you could simply do something like:
def is_square(matrix):
return all(len(row) == len(matrix) for row in matrix)
Upvotes: 1