简体   繁体   中英

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:])

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 , eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM