Reputation: 1511
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
Upvotes: 1
Views: 77
Reputation: 1
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.
Upvotes: 0
Reputation: 184395
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.)
Upvotes: 2
Reputation: 155684
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, e.g. 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
Upvotes: 2