 Trying to solve infinite sum in python core | Sololearn: Learn to code for FREE!

0

# Trying to solve infinite sum in python core

My code seems to add only the first two elements Instead of all of them Code : change the function def adder(x, y,*args): print(x+y) adder(2, 3) adder(2, 3, 4) adder(1, 2, 3, 4, 5) Output: 5 5 3 Instead of : 5 9 15 Description: Given a function that takes 2 arguments and returns their sum. But we get an error when we want to sum more than 2 numbers. Change the function and complete the code so that the function sums as many numbers as are input.

+3

So you need to add all the number in the parameter right? well, you can see, in this function, def adder(x, y,*args): there is a *args(arguments) in the function parameter .Using *args as a function parameter enables you to pass an arbitrary number of arguments to that function. The arguments are then accessible as the tuple args in the body of the function. so when you give adder(1, 2, 3, 4, 5) the value of x becomes 1 ,y becomes 2 and args becomes (3,4,5) So as args return tuple ,you can use sum function to get the sum of all the value inside args. like this: sum(args) so now I think you can do this easily.

+2

we know that sum(args) provides the sum of the complete tuple . Using that and just eliminating y is a much more easier method in my opinion. def adder(x,*args): t = sum(args) print( x + t) adder(2, 3) adder(2, 3, 4,) adder(1, 2, 3, 4, 5) Hope this helps you out.

0