Ines
Ines

Reputation: 11

Sum of integers in a list in Python - def Recursive_function(one-argument)

Sum of the elements (representing integers) in a list. For ex. A = ["xx", "3e", "5", "44"]

My function returns 49. So, the RECURSIVE one should do the same.

I implemented the ITERATIVE version successfully.

def add_iter(my_list):
    t = 0
    for x in my_list:
        if x.isdigit() == True:
            t+= int(x)
    print(t)

I would like to convert it to RECURSIVE function.

Upvotes: 0

Views: 85

Answers (4)

Ajax1234
Ajax1234

Reputation: 71451

Shorter recursive solution:

def add_iter(d):
  return (0 if not d[0].isdigit() else int(d[0]))+(0 if not d[1:] else add_iter(d[1:]))

A = ["xx", "3e", "5", "44"]
print(add_iter(A))

Output:

49

Upvotes: 0

AnsFourtyTwo
AnsFourtyTwo

Reputation: 2518

Try this:

def add_recursive(my_list):
    if my_list:
        x = my_list[0]
        if x.isdigit():
            return int(x) + add_recursive(my_list[1:])
        else:
            return add_recursive(my_list[1:])
    else:
        return 0


A = ["xx", "3e", "5", "44"]
add_recursive(A)
# 49

Upvotes: 0

fixatd
fixatd

Reputation: 1404

The recursive version functions similarly where you only iterate through each element before recursing to the remainder of the list. Your base case would be when the list only has one element left. I would suggest making a helper class to ensure that your values are valid numbers

# Helper function to clean up int value
def zero_or_value(value):
  try:
    return int(value)
  except ValueError as err:
    # Handler err here if you want
    pass
  return 0


def recursive_add_iter(my_list):
  if not my_list: # Return 0 if list is empty
    return 0
  elif len(my_list) == 1: # Base case, try converting last element
    return zero_or_value(my_list[0])

  return zero_or_value(my_list[0]) + recursive_add_iter(my_list[1:])


A = ["xx", "3e", "5", "44"]

print(recursive_add_iter(A))

Upvotes: 0

blue note
blue note

Reputation: 29071

Since it's an exercise, i'm not writing the answer, but giving some hints

  • The sum of an empty list is zero
  • the sum of a non-empty list is (the first element) + (sum of the rest of the list)
  • the first element might be ignored if it's not a number

Upvotes: 2

Related Questions