Secret Santa
Secret Santa

Reputation: 15

How can i sum every nth number from list recursively?

I want to add every nth number from list recursively, but NOT the first number, so lets say I have a list [1, 2, 3, 4, 5, 6] and I want to add every 2nd number, so that would mean I need to add 2 + 4 + 6 but if I want to add every 3rd number, then it should add 3 + 6.

So right now I have this much, I want to add every 2nd number so that means I want to add 2, 4 and 6, but I can't seem to figure out why it doesn't work, what should I do differently?

def getsum(numbers):
    if len(piece)==0:
        return 0
    else:
        return getsum(numbers[2:]) + numbers[0]  
print getSum([1, 2, 3, 4, 5, 6])

Upvotes: 0

Views: 1110

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

You can pick out the nth number, then recursively slice off everything after that when you call the function again

def get_sum(numbers, n):
    if len(numbers) < n:
        return 0
    return numbers[n-1] + get_sum(numbers[n:], n)

For example with n = 2 and n = 3 respectively

>>> get_sum([1, 2, 3, 4, 5, 6], 2)    # 2 + 4 + 6
12
>>> get_sum([1, 2, 3, 4, 5, 6], 3)    # 3 + 6
9

Upvotes: 2

Related Questions