Just started to deal with recursion - I don’t understand everything in it yet. I think that i don\'t use a basic conditional, but i don\'t have any idea how to write it. The pro
Maybe this approach can help you understand.
It starts from the first element and sums the rest every x
ones.
That is my assumption, as you haven't provided an input and its desired output as an example.
In case you need to start from the x
th element the code can be easily modified, I leave it to you to experiment with it.
def sum_elements(nums, x) -> int:
if x>0 and x<=len(nums):
return nums[0] + sum_elements(nums[x:], x)
return 0
lst = [1, 2, 3, 4, 5, 6]
print(sum_elements(lst, 2))
print(sum_elements(lst, 3))
print(sum_elements(lst, 0))
produces
9
5
0
Note: it just demonstrates recursion, but it's not optimal for a number of reasons.
Also it discards negative values of x