'how do i adjust my code to become a recursive reverse sum loop
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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | juanpa.arrivillaga |
Solution 2 | Devil Ishere |