Trying to solve infinite sum in python core | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.

19th Apr 2021, 7:40 AM
Simisola Osinowo
Simisola Osinowo - avatar
6 Answers
+ 8
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.
1st Aug 2021, 8:23 AM
Aayushi Jha
Aayushi Jha - avatar
+ 5
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.
19th Apr 2021, 7:47 AM
The future is now thanks to science
The future is now thanks to science - avatar
0
Thanks
19th Apr 2021, 8:10 AM
Simisola Osinowo
Simisola Osinowo - avatar
0
def adder(x, *args): for item in args: x+=item print(x)
14th May 2021, 12:55 PM
Volodymyr Shylov
Volodymyr Shylov - avatar
0
The shortest way, I guess, is like def adder(x, *y): print(x+sum(y))
7th Oct 2021, 9:21 PM
Voitsekh Ken
Voitsekh Ken - avatar
- 1
#change the function def adder(x, y,*args): print(x+y) sum(args) adder(2, 3) adder(2, 3, 4) adder(1, 2, 3, 4, 5) Like this
19th Apr 2021, 8:01 AM
Simisola Osinowo
Simisola Osinowo - avatar