Calculate the number of even numbers in a tuple recursively

Asked

Viewed 701 times

0

I need help creating a recursive function that finds and adds the even elements of a tuple, I would really 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:])
  • Sorry buddy, really it’s just to count the even elements of Tuplo recursively.

  • And why yours if is commented?

  • Because I don’t know how to use in this case

1 answer

2


Just check if the value is even by checking the rest of the division by 2. If zero is even; if 1 is odd. When even, you must add 1 plus the number of even numbers in the rest of the tuple; if odd, you must return only the even number amount 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 a specialization of the whole type, being False equal to zero and True equal to 1, could do only:

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

Browser other questions tagged

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