0

I am new to Python and just learned function and variable length arguments.

I am trying to write a function that takes any number of arguments, and sums all numeric types, in consideration of the argument could be any type, including a list of a list of a list.

The following code is what I came up with so far:

def sum_all(*args):
    if len(args) == 0:
        return None

    ls = list(args)
    sum = 0

    for elem in ls:
        if isinstance(elem, (list, tuple)):
            for i in elem:
                ls.append(i)
        elif isinstance(elem, (int, float)):
            sum += elem

    return sum

When I call the function as followed:

test1 = [1, 3, 5, 7, 9]
test2 = [1, 2, [3, 4], 5, 6, 7, [8, 9]]
test3 = [[1, 2, "string", {"error": 404}, [3, [4, 5]]], 6, 7, [8, [9, [10, 11]]], (12, 13, 14)]

print(sum_all(test1))
print(sum_all(test2))
print(sum_all(test3))

It returns the result as expected:

25
45
105

It works fine, but it basically just appends everything to the end of the original list, intuitively speaking, it should be inefficient.

I understand the saying - "if the code works, don't touch it" - but is there a way to make it more elegant?

If it is not too much to ask, please provide one without importing modules and one with (if there is one).

  • Hi Lonesome Coder! Welcome to StackOverflow. If the code works, and you just want to get someone to review it, and maybe give some tips on making it faster/better/more pythonic, you should ask on code review. See https://codereview.stackexchange.com/help/how-to-ask – Mark Jul 12 '23 at 03:53
  • Have a look at the answer of dtlam in this posting: https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists – tfv Jul 12 '23 at 03:58
  • @Mark Thank you so much for the warm welcoming. Noted! I will post the question on code review next time. – The Lonesome Coder Jul 12 '23 at 04:28
  • @tfv Thank you so much. However, the author himself suggested that the method is inefficient and should be avoided. – The Lonesome Coder Jul 12 '23 at 04:34

1 Answers1

1
  1. first you can define a function to flatten the list
def flatten(l):
    for el in l:
        if isinstance(el, (list, tuple)):
            yield from flatten(el)
        elif isinstance(el, (int, float)):
            yield el
  1. then calculate the sum
test1 = [1, 3, 5, 7, 9]
test2 = [1, 2, [3, 4], 5, 6, 7, [8, 9]]
test3 = [[1, 2, "string", {"error": 404}, [3, [4, 5]]], 6, 7, [8, [9, [10, 11]]], (12, 13, 14)]

print(sum(list(flatten(test1))))
print(sum(list(flatten(test2))))
print(sum(list(flatten(test3))))

then the output is

25
45
105
Xiaomin Wu
  • 400
  • 1
  • 5