Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use recursion to sum up a list of numbers up until a certain index

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))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading