Q2. Define a function
make_accumulator
that returns an accumulator function, which takes one numerical argument and returns the sum of all arguments ever passed to accumulator. Use a list and not a nonlocal statement.
Below is the solution:
def make_accumulator():
"""Return an accumulator function that takes a single numeric argument and
accumulates that argument into total, then returns total.
>>> acc = make_accumulator()
>>> acc(15)
15
>>> acc(10)
25
>>> acc2 = make_accumulator()
>>> acc2(7)
7
>>> acc3 = acc2
>>> acc3(6)
13
>>> acc2(5)
18
>>> acc(4)
29
"""
lst = []
def accumulate(n):
lst.append(n)
length = len(lst)
total = 0
for index in range(length):
total = total + lst[index]
return total
return accumulate
Can we improve this solution?