Home > Mobile >  def xxx(*args) where arguments may be any object. How to get sum of numbers in arguments?
def xxx(*args) where arguments may be any object. How to get sum of numbers in arguments?

Time:10-09

I have a function with arbitrary number of arguments and need to add those arguments when they are numbers or can be turned to numbers. Example:

def object_sum(*args):
    pass

print(object_sum(3, 'sun', '5', ['5', 'earth'], (5, '5')))
#Would print 23

CodePudding user response:

Assuming you want to catch the nested integers, do:

from collections.abc import Iterable


def object_sum(*args):
    def flatten(l):
        # https://stackoverflow.com/a/2158532/4001592
        for el in l:
            if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
                yield from flatten(el)
            else:
                try:
                    yield int(el)
                except ValueError:
                    yield 0

    return sum(flatten(args))


print(object_sum(3, 'sun', '5', ['5', 'earth'], (5, '5')))

Output

23

CodePudding user response:

Test if the argument is a list or similar, if yes, recurse into it, if not, try to convert it to an integer:

def object_sum(*args):
    result = 0
    for arg in args:
        arg_type = type(arg)
        if arg_type in (list, tuple, set, range):
            result  = object_sum(*arg) # The asterisk is important - without it, the recursively called function would again call itself, and we'd get a RecursionError
        else:
            try:
                result  = int(arg) # Try to convert to int
            except ValueError:
                pass # arg is not convertable, skip it
    return result

print(object_sum(3, 'sun', '5', ['5', 'earth'], (5, '5')))

Output:

23
  • Related