Calculate the number of even numbers in a tuple recursively

0

I need help to create a recursive function that finds and adds the even elements of a tuple, I would greatly appreciate the help.

def conta_pares(t):
   '''conta_pares : tuplo -> inteiro
   recebe tuplo de inteiros e devolve o numero de elementos pares no tuplo'''
   if t == ():
      return 0
   else:
      #t = (t[1:])
      #if a % 2 == 0:
      return t[0] + conta_pares(t[1:])
    
asked by anonymous 17.12.2018 / 16:32

1 answer

2

Just check if the value is even by checking the rest of the division by 2. If it is zero it is even; if 1 is odd. When even, you must add 1 plus the number of even numbers in the remainder of the tuple; if it is odd, it should return only the number of even numbers in the rest of the tuple.

def pares(t):
    if not t:
        return 0

    par = (t[0] % 2 == 0)

    if par:
        return 1 + pares(t[1:])
    else:
        return pares(t[1:])

Or, in a simplified form:

return (1 if par else 0) + pares(t[1:])

If you consider that the Boolean type in Python is an integer-type specialization, being False equal to zero and True equal to 1, you could just do:

def pares(t):
    if not t:
        return 0            
    return (t[0] % 2 == 0) + pares(t[1:]
    
17.12.2018 / 17:06