'Isinstance function to check the elements given fits in my matrix
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 \
(....)
Solution 1:[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
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark |
| Solution 2 |
