Can anyone help write this program in python that involves tuples?

Asked

Viewed 53 times

0

I am writing the python "check" function, which takes an argument of any type and returns True if that argument is a Tuplo whose elements are pairs (2-element doubles), where the first element is a name (a string) and the 2nd element is an age (an integer). Otherwise it returns False. This is what I came to:

def verifica(variavel):
    if isinstance(variavel, tuple):
        if isinstance(variavel[0], str) and isinstance(variavel[1], int):
            return True
        else:
            return False
    else:
        return False

The result should be for example:

>>> verifica( (('Maria', 38), ('Miguel', 17), ('Tiago', 18), ('Sara', 19)) )
>>> True

>>> verifica( ((54, 38), ('Miguel', 17), ('Tiago', 18), ('Sara', 19)) )
>>> False

I’m not getting this result, someone can help?

  • 1

    This question has already been asked, as you can see, but I would like to point out that your first example is wrong. The function should not return True if the input is a tuple containing 4 tuples. The actual text of the question is quite clear: only must return true if it is a tuple with 2 values, being a string and an integer.

  • Yes, the question has already been asked, but the solutions indicated are not the one sought. , hence I am trying to seek help as well, thank you if I can give some indication I would appreciate.

  • 1

    Maybe not the wanted one, but it answered exactly what was asked. If the solutions there do not meet, I recommend that you edit the question and detail better what should be done. Even the code you posted seems to be the same as the one another user responded to there, so always try to give credit. You can read other details in the Site Terms of Service.

  • The answer to the other question has been edited. Check if it helps you.

  • It’s not the solution I want, but thank you very much :) What I’m looking for is something like: def verifies(variable): for all tuples #If to know if it’s a tuple if type(variable) is tuple: #If it’s tuple, let’s check if the first element is str and the second int if (type(variable[0]) is str) and (type(variable[1]) is int): Return True Else: Return False Return False

No answers

Browser other questions tagged

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