You need to write a function on python that is called an indefinite number of times, each time it takes a number and returns their sum, for example sum (1) (2) (3) == 6. I found the code for javascript, but I did not find how to redefine it in python __str __ method for the function. How can I override a method or is there another solution?
The code I tried to write:
def sum(n):
total = n
def f(k):
nonlocal total
total += k
# f.__str__ = lambda : print(total) # no
return f
return f
print(sum(1)(2)(3))
This is working javascript code:
function sum(a) {
let currentSum = a;
function f(b) {
currentSum += b;
return f;
}
f.toString = function() {
return currentSum;
};
return f;
}
alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6
alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15