Home > OS >  I need to recursively get the half of even integers in a list in python
I need to recursively get the half of even integers in a list in python

Time:08-29

I've gotten most of my code, but the only thing I'm struggling with is getting the odd numbers out of my created list. Here is my code:

def halfEven(x):
    if not x:
        return []
    else:
        i = x[0]
        if i % 2 == 0:
            i //= 2
        elif i % 2 == 1:
            x.remove(i)
    res = [i]   halfEven(x[1:])
    return res

While testing with halfEven([0,5,2,99,555,6,2,4]) I get [0,5,99,3,1,2] but I want the answer [0,1,3,1,2]. Any nudges in the right direction would be much appreciated.

CodePudding user response:

I solved the issue by creating a list to store the answers. Here is the code:

def halfEven(x):
    if not x:
        return []
    else:
        i = x[0]
        evens = []
        if i % 2 == 0:
            i //= 2
            evens.append(i)
    res = evens   halfEven(x[1:])
    return res

Thank you for the help. I know it was an easy answer but I was struggling lol

CodePudding user response:

You don't have to create a list to store the answers -

def halfEven(x):
  if not x:
    return []
  elif x[0] % 2 == 0:
    return [x[0] // 2, *halfEven(x[1:])]
  else:
    return halfEven(x[1:])

But really the consumer should be able to use the values as they are generated -

def halfEven(iterable):
  for x in iterable:
    if x & 2 == 0:
      yield x // 2

If you want a more functional implementation, consider itertools -

from itertools import filterfalse

def evens(iterable):
  return filterfalse(lambda x: x % 2, iterable)

def halfEven(iterable):
  return map(lambda x : x // 2, evens(iterable))

You can even use operator module for functional forms of % and // -

from itertools import filterfalse
from operator import mod, floordiv

def evens(iterable):
  return filterfalse(lambda x: mod(x, 2), iterable)

def halfEven(iterable):
  return map(lambda x : floordiv(x, 2), evens(iterable))
  • Related