Home > Software engineering >  How to use recursion to sum up a list of numbers up until a certain index
How to use recursion to sum up a list of numbers up until a certain index

Time:05-15

I have to write a code that makes use of recursion to sum numbers in a list up until the index is equal to a pre-determined integer value. i.e.

  list = [1,4,8,9]
    int = 2
    sum = 1   4 (index 0 and 1)

below is my code so far, but I am struggling with the logic with my first if statement and hence it isn't working. I get the error 'int' object has no attribute 'index' Any help would be greatly appreciated (PS very new to coding - so sorry if my code isn't the best)!

# Sum Recursion

def Arecursion(Alist,index):

    if index > 0:       # if the index point in the list matches the integer return the sum
        return Alist[index]   Arecursion(Alist,index-1)
    else:
        return 0

list_test = [1,4,6,7,10]
int_test = 2
print(Arecursion(list_test,int_test))

CodePudding user response:

You are making it more complex that you need to. You just need a base case — the current index is too big, and the recursion — the value at the current index plus the rest:

def sum_rec(l,max_index, i=0):
    if i >= max_index or i >= len(l):          # base case
        return 0
    return l[i]   sum_rec(l, max_index, i 1)   # recursion


sum_rec([1, 2, 3, 4], 0)
# 0
sum_rec([1, 2, 3, 4], 1)
# 1
sum_rec([1, 2, 3, 4], 2)
# 3
sum_rec([1, 2, 3, 4], 3)
#6
  • Related