Sum with level

Posted on Tue 28 March 2017 in Puzzles

In [1]:
class SumLv:
    def __init__(self, depth):
        self.depth=depth
        self.lv=self.depth
        self.s=0
    def __call__(self, *args):
        '''
        Empty call to return value
        Non-empty call to add values
        '''
        if args:
            self.s+=sum(args)
            self.lv-=len(args)
            if self.lv==0:
                return self.ret()
            elif self.lv<0:
                self.ret()
                raise Warning('Too many arguments!')
        else:
            self.ret() # Empty call invoking ret()
        return self
    def ret(self):
        '''Return the sum and reset level & sum'''
        self.lv=self.depth
        self.finalsum, self.s=self.s, 0
        return self.finalsum
    def __repr__(self):
        return "level={}, sum={}".format(self.lv, self.s)
In [ ]:
sum4=SumLv(4)
In [3]:
print(sum4(1, 2, 3, 4))
print(sum4(1)(2, 3, 4))
print(sum4(1)(2)(3, 4))
print(sum4(1)(2)(3)(4))
10
10
10
10
In [4]:
try:
    sum4(1,2,3,4,5)
except:
    print(sum4.finalsum)
15
In [5]:
sum4(1,2)
Out[5]:
level=2, sum=3
In [6]:
sum4(3)
Out[6]:
level=1, sum=6
In [7]:
sum4(4)
Out[7]:
10