Home > Mobile >  How to write an iterative function in a recursive manner
How to write an iterative function in a recursive manner

Time:12-31

I need to sum the variables in a list if they are integers and ignore if they are strings.

I have written one for the iterative function:

x = ['apple', 2, 'car', 4, 'free',25]

int_sum = 0 

for i in x: 
    if isinstance(i, int):
        int_sum  =i

print(int_sum)

I need to write the same as a recursive function, how can I do this?

CodePudding user response:

You can do like this:

def main():
  x = ['apple', 2, 'car', 4, 'free',25]
  def f(index):
    if index >= len(x):
      return 0
    if isinstance(x[index], int):
      return f(index 1)   x[index]
    return f(index 1)
  print(f(0))
main()
    

CodePudding user response:

Each invocation of the function should add one element to the sum, and then shrink the list by one and call itself to get the sum for the remainder (if any):

def int_sum(x):
    return (
        (x[0] if isinstance(x[0], int) else 0)
          (int_sum(x[1:]) if x[1:] else 0)
    )


print(int_sum(['apple', 2, 'car', 4, 'free', 25]))  # 31

CodePudding user response:

A recursive version of this function would look something like

def total(data):
    # If the remaining list is empty, no further ints to accumulate
    if not data:
        return 0

    # Process the first value in the data
    first = data[0]

    # If this first value is an integer, add it to the total
    # then recursively process the remaining data excluding this value
    if isinstance(first, int):
        return first   total(data[1:])

    # First value was not an int, discard it and process
    # the remaining data recursively
    else:
        return total(data[1:])

using your example

>>> total(['apple', 2, 'car', 4, 'free',25])
31

As an aside, going back to your iterative version I'd prefer to use a generator expression in this case

def total(data):
    return sum(i for i in data if isinstance(i, int))
  • Related