gbrish
gbrish

Reputation: 61

how to sum a list of arguments with recursion?

I am trying to write a function that takes any number of arguments and then sums them using recursion ( I am not using the built in sum function. I am assuming arguments will be int. )

But my base case doesn't stop it from recursing! Any hints?

def sum_all(*args):
 if args == ():
    return 0
 else:
    return args[0] + sum_all(args[1:])

Upvotes: 1

Views: 449

Answers (1)

AChampion
AChampion

Reputation: 30258

You need to expand the args in your recursion, and not args would be sufficient for the test:

def sum_all(*args):
    if not args:
        return 0
    return args[0] + sum_all(*args[1:])
                             ^

Python 3 also added some new syntax that allows you to unpack *args, e.g.:

def sum_all(*args):
    if not args:
        return 0
    a, *b = args
    return a + sum_all(*b)

Upvotes: 7

Related Questions