Filter elements of a tuple based on a value in a certain index

0

I want to write a function in Python, call separates, which receives a tuple tup whose elements are pairs (double of 2 elements), where the 1st element is a name (a string) and the 2nd element is an age (an integer), as described in the previous exercise.

The function should return 1 tuple with two elements:

  • 1 tuple with the elements of the original tuple where the age is less than 18.
  • 1 tuple with the elements of the original tuple where the age is greater than or equal to 18.
  • Your function should check if the argument you received is correct (use exercise 1 function to do this check). If the argument is not correct, an error should be generated with the raise statement ValueError ('separa: argument incorrect.').

Example:

>>> tup = (('Maria', 38), ('Miguel', 17), ('Tiago', 18), ('Sara', 19))
>>> menores, maiores = separa(tup)
>>> menores
(('Miguel', 17),)
>>> maiores
(('Maria', 38), ('Tiago', 18), ('Sara', 19))

>>> separa(())
((), ())

>>> separa((('Maria', 38), ('Miguel', 17), ('Tiago', 18), ('Sara', 19.7)))
              ….
builtins.ValueError: separa: argumento incorrecto.
    
asked by anonymous 07.11.2018 / 03:06

1 answer

3

If you have a tuple in the form

valores = (('Maria', 38), ('Miguel', 17), ('Tiago', 18), ('Sara', 19))

You can list the items that have the second value less than 18 as follows:

menores = tuple(it for it in valores if it[1] < 18)

And greater than or equal to 18 in a similar way:

maiores = tuple(it for it in valores if it[1] >= 18)

So, considering the verifica function, which was defined in the previous exercise - that is, let's consider that you already did the previous exercise and have this function working (its implementation is not part of this question), you can write a function in the form:

def separa(tuplo):
    if not verifica(tuplo):
        raise ValueError(’separa: argumento incorrecto.’)

    menores = tuple(it for it in tuplo if it[1] < 18)
    maiores = tuple(it for it in tuplo if it[1] >= 18)

    return (menores, maiores)
    
07.11.2018 / 11:41