How to validate if a value is a tuple having a string and an integer?

Asked

Viewed 872 times

0

I want to write a function that takes an argument (any type) and returns true if the argument is a tuple (double elements, double elements of 2), where the first is a name (str) and the second is an age (int). Otherwise it returns False.

My first draft is:

def verifica(tuplo):

    tuplo = ( (joao,39), (paulo,15), (andre,14), (simao,21) )    

resultado = isinstance(tuplo[0],str)

return (isinstance(tuplo[0],str)    
return (isinstance(tuplo[1],int)   

I know I must have a cycle IF. When calling the function, isn’t it supposed to have 2 fields? Something like name and age?

Ex: verifica(joao,39) - in case the combo is in the Tuplo, returns a true?

  • 2

    Start by confirming the code indentation, and change it so it looks exactly like the one you have in your editor.

  • I put the code just like this in my editor. By the way, I use python 3.3 and Wing IDE 101 as compiler.

  • 2

    Seems unlikely, because the way the code is in the question, you have return out of function verifica. Soon I assume it’s all function code verifica but only you can confirm.

3 answers

3

I’ll start from the premise that you forgot to put the quotes in your strings. Then the correct tuple would be:

(('joao', 39), ('paulo', 15), ('andre', 14), ('simao', 21))

From this you need to know how to test the type of a variable correctly. You can use the method type() and compare directly with the type you want, for example:

if type(variavel) == tuple:
    print('É uma tupla')

However it is worth remembering that in this way there is no verification of subclasses, ie in the example above, if variavel is from a subclass of tuple print would not run because there is no subclass check.

To perform this check just use the method isinstance(), which checks if the variable is of the asked type or if it is of some subclass of the asked type. Example:

if isinstance(variavel, tuple):
    print('É um tupla ou subclasse de tupla')

The use of one or the other will depend on the requirements of your software, but as a general rule I use isinstance() because the subclass is likely to behave like the parent class.

That said, all you would need to do is test the 4 requirements you want, which are:

  1. Variable is a tuple
  2. This tuple has only two elements
  3. First element of the tuple is str
  4. Second element of the tuple is int

You’d have something like:

def verifica(variavel):
    return isinstance(variavel, tuple) \
        and len(variavel) == 2 \
        and isinstance(variavel[0], str) \
        and isinstance(variavel[1], int)

For curiosity purposes, rather than using and you can use the method all() returning True only if all received parameters are also True. The whole example would look like this:

def verifica(variavel):
    return all((
        isinstance(variavel, tuple),
        len(variavel) == 2,
        isinstance(variavel[0], str),
        isinstance(variavel[1], int)
    ))

dados = (
    ('joao', 39),     # True
    (b'andre', 14),   # False pois 1º elemento não é str
    ('paulo', 15.3),  # False pois 2º elemento não é int
    ('simao', 21, 0)  # False pois não contém exatamente 2 elementos
)

for d in dados:
    print(verifica(d))

Repl.it with code working.


Edit: added tuple size check (Tip: @Anderson-carlos-woss).


Edit 2

As there still seem to be doubts about how to apply the function verifica() for all elements of a sequence, and not just one element, I will elaborate.

The function verifica() receives a tuple and checks if the tuple pattern is correct:

tupla_valida = ('Tupla válida', 0)
verifica(tupla_valida)  # True

If you want to check all the tuples of a sequence, you can scroll through this sequence using a loop for and test one by one. If some of them are False then you choose what your program should do about it.

Example, check if the sequence contains only valid tuples:

tuplas = (('joao', 39), ('paulo', 15), ('andre', 14), (0, 'Inválida'))

todas_validas = True  # Valor inicial

for tupla in tuplas:
    if not verifica(tupla):
        # se alguma tupla for inválida atribui False e sai do loop
        todas_validas = False
        break

if todas_validas:
    print("Todas as tuplas são válidas")
else:
    print("A sequência contém alguma tupla inválida")

Repl.it with code working.

If you have any questions about the above code, study a little about the for and the break.

I will leave as an example for study, an alternative to the previous code that uses the method all() previously mentioned and list comprehensions to achieve the same result.

tuplas = (('joao', 39), ('paulo', 15), ('andre', 14), (0, 'Inválida'))

# aplica a função `verifica` em todos os elementos da tupla e passa
# a lista resultante para o método `all`
# nesse caso o método `all` recebe: (True, True, True, False)
todas_validas = all([verifica(tupla) for tupla in tuplas])

if todas_validas:
    print("Todas as tuplas são válidas")
else:
    print("A sequência contém alguma tupla inválida")

Repl.it with code working.

  • Fernando, thank you for your attention. Some details to clarify. The purpose is essentially to write verfica (('Joao',15)) and if this condition is in Uplo.. ie the name Joao with the age pair 15, then the progress returns the false.

  • I cannot use prints, only same.

  • Did you ever run the code? The function I wrote does just that... You can pass it to her verifica(('João', 15)) and she will return True if it is valid, or False if invalid. Print is for demonstration only.

  • I think I get it... When you say "in case the condition is on Tuplo" you want to know if there is a tuple ('João', 15) within the values of dados?

  • It is unclear if you want to validate the data types inside the tuples or if you want to search in these tuples...

  • Imagine, I have a tuple with the following data: Tuplo = ( (Joao,39), (paulo,15), (Andre,14), (simao,21) ) ««« now the goal of the program is to get me up and running.. and write a name any and an age, IF and ONLY IF this pair is in the Uplo is that it returns truth, if any of the data.. either the name or age, or both are not in Tuple, so it returns the false.

  • That is, if I now arrive and write check(('paul',20)) it should return a false because the age n corresponds to the pair in Tuple.

  • Your question implies that you want to validate whether the elements of the main tuple are in the format tuple(str, int). Your question: I want to write a function that takes an argument and returns true if the argument is a string , where the first is a name (str) and the second is an age (int). You could edit the question to clarify better

  • Fernando, is there a chat on this platform? can I explain better not to spammar comments

  • https://chat.stackexchange.com/rooms/85348/duvida-exercicio-python-tuplos

  • You must have 20 Reputation on The Stack Exchange Network to talk here. Is there any alternative? can I email you?

  • You want to find out if the tuple passed in function verfica is contained in the tuple that contains your data. That’s it?

  • The problem I have at hand is the following, asks me to write a Function in python that takes an argument of qq value and returns TRUTH if the argument is a TUPLE of even elements (double of two elements), where the 1 element is a name (str) as I said and 2 is the age (int). Otherwise RETURN false. example: verifies(('Joao',39)) true (because we have this pair in the data) verifies((('Joao',40)) false (because we have a Joao but it is 39 years old.

  • Your description says one thing and your example says another. In your description you speak to create a function that validates whether the argument is a tuple in the format tuple(str, int) and in the example you are making an "exists" in the tuple. You should edit your question to make it clearer.

  • You’re right, I was complicating.

  • in this case, its initial resolution was correct: def verifies(variable): Return all(( isinstance(variable, tuple), isinstance(variable[0], str), isinstance(variable[1], int) )) it is possible to remove the data and the cycle is and will work in the same?

  • I am complementing the answer to check if the value exists in tuples

  • No need, my example was wrong, I was complicating.

  • The idea is to even write the function checks(('name', age)) where the name is a str and the age is an int, if yes, of true, if not false. I’m trying to run only the first part of the program without including the data and the cycle is, but not the, it’s possible?

  • Fernando, in the resolution of the Matheus below, how do we add the arguments? Note the example I gave you, I want to avoid "builtins.Typeerror: verifies() takes 1 positional argument but 4 Were Given"

  • the function verifica() takes only 1 argument, one tuple. If you want to test several tuples make one for and test all the tuples within its sequence. The code of my answer does this.

  • In the context of your code, is it possible to remove the data? and is it possible to use Return no for instead of print? Another voisa, the "d" represents what exactly?

  • def verifies(variable): Return all(( isinstance(variable, tuple), isinstance(variable[0], str), isinstance(variable[1], int) ) for v in variable: Return(verifies(v))

  • da me erro: Syntax Error: 'Return' Outside Function:

  • 1
  • Fernando, that the Return is outside the function I understood, which is the correct syntax to have the Return to work inside the function?

  • Fernando, my program can’t use prints, all the examples presented have, I don’t know how to apply Return properly, I don’t know enough syntax. Forget my initial question, Tuplo is not to be set within the program as I wrote. You should rather test a sequence of tuples using the function in the shell. Can you demonstrate an example with these specs? 1ºyou cannot have prints. 2ºshould not have the Tuplo defined with data within the function 3º should test the sequence in the shell example: verifies(('paul',19), ('maria',23),('Joao',53)) «« returns a true pk all

  • tuple parameters meet str and int req

Show 23 more comments

0

If I understand correctly, you want a function that takes the code and sees if it is tuple type, if it is, take the 0 position and see if it is string and position 1 and see if it is int... Follows the code:

def verifica(variavel):
    #If para saber se é uma tupla
    if type(variavel) is tuple:
        #Caso seja tupla, vamos verificar se o primeiro elemento é str e o segundo int
        if (type(variavel[0]) is str) and (type(variavel[1]) is int):
            return True
        else:
            return False
    return False

verifica(('matheus',1))

PS: I used python 2.7

  • Matheus thank you for the contribution. just lacks a nuance. there has to be a Tuple with data, as I wrote.. and when I put the data in the function, in addition to the condition of the variables that the writing program does, it still has to check if the name data older are in the.

  • Matheus ignore what I wrote, when talking to Fernando I understood that I was complicating my need, now I only have one question regarding his resolution : builtins.Typeerror: verifies() takes 1 positional argument but 4 Were Given, Is it not possible to use several arguments in the function? ex: verifies((2ª Matheus', 21), (2ª Andre', 32), ('maria', 17), ('Joaquim', 20))

  • The way it is is only to accept a tuple. what you can do and play a for inside the function and pass a tuple with various values

  • that’s exactly what I need, Ernando still hasn’t answered me, but in his case he used the print, I can only use Return and in the cycle for, I don’t understand the variable "d" ?

  • for v in variable: if type(variable) is tuple: if (type(variable[0]) is str) and (type(variable[1]) is int): Return True Else: Return False Return False Return(checks(v))

  • I cannot properly apply the for cycle, it still shows the same error.

Show 1 more comment

0

Use the function isinstance passing each element and type. It follows a function that generalizes this idea:

def verificar_tipos(tupla, tipos):
    return all(isinstance(elemento, tipo) for elemento, tipo in zip(tupla, tipos))

You use it this way:

verificar_tipos(('joao', 23), (str, int)) # retorna True
verificar_tipos(('joao', 23), (str, str)) # retorna False

If you have a list of tuples, just make a call to verificar_tipos for each of them:

def verifica(tuplas, tipos):
    for tupla in tuplas:
        if not verificar_tipos(tupla, tipos)
            return False
    return True

You’d wear it like this:

verifica([('paulo',19), ('maria',23),('joao',53)])
  • Gabriel, thank you for your contribution. My function should test several parameters at once, as I indicated in the example to Ernando: verifies (('Paul',19), ('Mary',23),('John',53)) «« returns a true. The example of Matheus does what I want but only for 1 parameter, I want to have several, I have been told that I should use a FOR cycle, but I don’t know how to fix the syntax for this. Can you help? note: can’t use prints, only Returns.

  • @Dominion I updated my answer with an example of code that does what you said, but I must warn you that the function of this site is not to give you ready codes. If you don’t know how to tie a bow for in Python, should study more on the subject, and not ask us to do everything for you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.