简体   繁体   中英

Python function that sums up lists and numbers

I'm learning python. How can I modify this function in python so that it adds up any number of integers, or lists or lists and numbers? Right now it adds only integers

def super_sum(*args):
    ''' Sums up the arguments
    '''
    total = 0
    for i in args:
        total += i
    return total

I want to be able to be able to call the function and get the values like shown below

print super_sum(20, 20) # outputs 40

or

a = [10, 20, 30, 40]
b = [100, 20]
print super_sum(a, b) # outputs 220

or

a = [10, 30, 50]
print super_sum(a, 50) # outputs 140

Simple approach would be recursion:

def super_sum(*args):
    ''' Sums up the arguments
    '''
    total = 0
    for i in args:
        if isinstance(i, (int, long)):  # On Py3, just isinstance(i, int)
            total += i
        else:
            total += super_sum(*i)
    return total

There are other ways to perform the test mind you, eg an EAFP pattern to avoid explicit type checking:

   for i in args:
        try:
            # Assume unpackable iterable...
            total += super_sum(*i)
        except TypeError:
            # If not iterable, assume numeric
            total += i

Define a helper function:

def try_sum(x):
    try:
       return sum(x)
    except TypeError:
       return x

Now super_sum() is just:

def super_sum(*args):
    return sum(try_sum(x) for x in args)

(If you want to write your own sum() that uses a for loop, instead of using the built-in, feel free to do that too. It would plug right in.)

def super_sum(*args):
    total = 0
    args = list(args)
    if len(args) == 1:
        args = args[0]
    for d in args:

        if isinstance(d, list):

            total += super_sum(d)
        else:
            total += d
    return total

print super_sum([1, 2, [3, 4], 5], 3, [2, 3])

Actually this is a little more than what you asked, it will add all numbers, and passed values can have list inside lists. it is called deep_sum usually.

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