I am supposed to use find out how to use "*" to sum up several values. For example:
sum_all(1, 2, 3, 4, 5)
15
sum_all(49, 51)
100
Given a general function like :
def sum_all(*args)
I am unsure how to implement the * within the code.
def sum_all(*args):
total = 0
for arg in args:
total += sum(arg)
return total
To be different from the others which i think posted at the same time as me, i'll explain and come up with another solution.
When doing *args you can look at it this way:
def sum_all([arg1, arg2, arg3, ...]):
Which would tedious to code and since you don't know how many parameters are given, you do *args instead, which dynamically takes a "endless" amount of arguments in a list format.
def sum_all(*args):
return sum(sum(arg) for arg in args)
This assumes the input is something along the lines of:
sum_all([1,2,3], [5,5], [10,10])
If not just skip one of the sums:
def sum_all(*args):
return sum(args)
sum(arg for arg in args) is just an verboser and way more innefficient version of just sum(args)You can treat the passed in variable as an iterable.
sum_nums = 0
for val in args:
sum_nums += val
A good read would be the top answer in this question.
In short:
def sum_all(*args):
return sum(args)
*args represent here a sequence of positional arguments, that you can later iterate over. Fortunately, builtin sum() takes single iterable as argument, so you can just pass it there.
More info you can find in docs: http://docs.python.org/2/faq/programming.html#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another
*argsis a list,**kwargsa dictionary. Just proceed as you would with any of them.tuplesince it doesn't support item assignment.