Reputation: 143
I have tab that is a tuple with three tuples and each has 3 elements that can only be 1, -1 or 0. I want a function to receive a tab an evaluate if it is True or False. This is what I came up with:
tab = ((0,0,-1),(-1,1,0),(1,0))
def board(tab):
if len(tab) != 3:
return False
else:
for row in tab:
if len(row) != 3:
return False
else:
for element in row:
if element not in (-1, 0, 1):
return False
else:
return True
The problem is that with the current tab it says true and it should be false. Also if anything is something besides 1,-1 and 0 it should return False and if I say tab = ((0,0,-1),(-1,1,0),(1,0,2)) it returns True. What's the problem?
Upvotes: 0
Views: 67
Reputation: 86
Your issue is your return statement of true, because of this return if any element is ok the entire function will return true, where in actuality you want the function to return false if any of the conditions are not met. You can remedy this by moving the return true to the end of the function so all of the elements must be tested before the function can be returned true. This is shown below and passes both of the test cases you mentioned
tab = ((0,0,-1),(-1,1,0),(1,0,2))
def board(tab):
if len(tab) != 3:
return False
else:
for row in tab:
if len(row) != 3:
return False
else:
for element in row:
if element not in (-1, 0, 1):
return False
return True
Upvotes: 1
Reputation: 520
You're looping through just one row!!! To understand, make the wrong row come first in the tuple and try it
Upvotes: 1
Reputation: 143
tab = ((0,0,-1),(-1,1,0),(1,0,2))
def board(tab): if len(tab) != 3: return False
for row in tab:
if len(row) != 3:
return False
for element in row:
if element not in (-1, 0, 1):
return False
else:
return True
Thanks guys!
Upvotes: 1