DEV Community

Lancelot03
Lancelot03

Posted on

A Chain adding function

We want to create a function that will add numbers together when called in succession.

add(1)(2) # equals 3
Enter fullscreen mode Exit fullscreen mode

We also want to be able to continue to add numbers to our chain.

add(1)(2)(3) # 6
add(1)(2)(3)(4); # 10
add(1)(2)(3)(4)(5) # 15
Enter fullscreen mode Exit fullscreen mode

and so on.

A single call should be equal to the number passed in.

add(1) # 1
Enter fullscreen mode Exit fullscreen mode

We should be able to store the returned values and reuse them.

addTwo = add(2)
addTwo # 2
addTwo + 5 # 7
addTwo(3) # 5
addTwo(3)(5) # 10
Enter fullscreen mode Exit fullscreen mode

We can assume any number being passed in will be valid whole number.

Sample Tests-

import codewars_test as test
from solution import add


@test.it("Basic tests")
def _():
    test.assert_equals(add(1), 1)
    test.assert_equals(add(1)(2), 3)
    test.assert_equals(add(1)(2)(3), 6)
Enter fullscreen mode Exit fullscreen mode

Solution- ###Python

class add(int):
    def __call__(self, n):
        return add(self + n)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)