0

I want to create a function that checks if the given tab fits or not. My matrix should be a 3x3 with 3 tuples, each with 3 integers.

I want this interaction to happen:

>>> tab = ((1,0,0),(-1,1,0),(1,-1,-1))
>>> tabuleiro(tab)
True
>>> tab = ((1,0,0),(’O’,1,0),(1,-1,-1))
>>> tabuleiro(tab)
False
>>> tab = ((1,0,0),(-1,1,0),(1,-1))
>>> tabuleiro(tab)
False

All I have right now is:

def tabuleiro(tab):

    return isinstance(tab, tuple) and len(tab) == 3 and \
           all((isinstance( l, tuple) and len (l) == len(tab[0])) for l in tab) and len (tab[0]) == 3 and \ 
(....)
Zoe
  • 27,060
  • 21
  • 118
  • 148
Cate C
  • 31
  • 6

2 Answers2

1

This is probably easier to read and reason about if you break it into one function for the group and another function for each member of the group. Then you could do something like:

def tab_is_valid(tab, valid_size=3):
    ''' is an individual member valid'''
    return len(tab) == valid_size and all(isinstance(n, int) for n in tab)
    
def tabuleiro(tab):
    ''' is the whole structure valid '''
    return all((
         isinstance(tab, tuple),
         len(tab) == 3,
         all(tab_is_valid(t) for t in tab),
     ))


tabuleiro(((1,0,1),(-1,1,0),(1,-1,-1)))
# True

tabuleiro(((1,0,1.6),(-1,1,0),(1,-1,-1)))
# False

tabuleiro(((1,0),(-1,1,0),(1,-1,-1)))
#False

tabuleiro(((1,0, 1),(-1,1,0),(1,-1,-1), (1, 1, 1)))
# False
Mark
  • 90,562
  • 7
  • 108
  • 148
  • 1
    Thank you for your answer! Still trying to find a easier way to do that with a single function. – Cate C Nov 15 '20 at 23:14
  • @CateC if you want a single function, you can simply copy the bit from the function to where it is called. If just becomes a little cumbersome to read. – Mark Nov 16 '20 at 00:32
  • how do I say that my values can only be (0,-1,1) in the function tabuleiro()? I've tried this, but something is wrong,I know. def tabuleiro(tab): return all((isinstance(tab, tuple) and len(tab) == 3 and \ all(isinstance(line,tuple) and len(line) == len(tab[0])) for line in tab) and len(tab[0]) == 3 and all((n in (0,1,-1) for line in tab for n in line)) – Cate C Nov 20 '20 at 01:30
0

In python3.10 and above, you can use pattern matching:

def tabuleiro(tab):
  match tab:
    case (int(),int(),int()),(int(),int(),int()),(int(),int(),int()):
      return True
    case _:
      return False

print(tabuleiro(((1,0,1),(-1,1,0),(1,-1,-1))))
# True

print(tabuleiro(((1,0,1.6),(-1,1,0),(1,-1,-1))))
# False

print(tabuleiro(((1,0),(-1,1,0),(1,-1,-1))))
#False

print(tabuleiro("string is not a tuple"))
# False

The line case _: does not change the value of variable _ (If I use another variable name, the value of this variable whould be the value of tab).

This line and the identation of last line return false are here not necessary, but I keep them for sake of readability.

user2987828
  • 1,116
  • 1
  • 10
  • 33