Home > Software engineering >  how do i adjust my code to become a recursive reverse sum loop
how do i adjust my code to become a recursive reverse sum loop

Time:02-10

I have a simple recursion method for reversing a list

lst = [1,2,3,4,5] will print as [5, 4, 3, 2, 1]

lst = [1, 2, 3, 4, 5]


def revlist(lst):
    if len(lst) == 0:
        return []
    else:
        return revlist(lst[1:])   [lst[0]]


print(revlist(lst))

Instead of it printing the reverse list i want it to add 5 4 3 2 1 but i dont know how to, at the end I should get 15 but not by just adding the sum of the list, only by adding at the last element and finishing at the first [0] element. Whatever I do to try and sum the array list it gives me errors and I dont really know how I can get any closer to code what I am trying to acheive.

CodePudding user response:

This is a strange requirement, but it could be accomplished like this:

def revsum(lst):
    if not lst: 
        return 0
    return lst[-1]   revsum(lst[:-1])

Of course, this is purely academic, and you should never use this in real Python code.

CodePudding user response:

This will work

lst = [1, 2, 3, 4, 5]
print(sum(lst[::-1]) 

It will reverse the lst using step counter(notice the two colons) then uses inbuilt sum function to add the list.

  •  Tags:  
  • Related