-4

What is desired is to

    def accumulator():
        def addition():
             something here 
             and others
        return addition

where

A = accumulator()

A(10) 
10
A(10)
20

using Message Passing such that every accumulator() will have the overall sum at the end.

I have no idea how to start. . . I would be really appreciative if you could help! Thanks

user3251511
  • 177
  • 1
  • 3
  • 15
  • What version do you use: Python 2 or Python 3? If you use Python 3, you can do this by closure. – HYRY Mar 30 '14 at 09:21
  • 2
    can you edit your question and finish your sentences? "Using Message Passing from", from what? You are using this function like an object in your example, do you need to write an object Accumulator? – Pawel Miech Mar 30 '14 at 09:25
  • @Aशwiniचhaudhary The input is not inside a list though. – user3251511 Mar 30 '14 at 09:26
  • @user3251511 You can use `itertools.count` or a while loop to get an infinite loop. And you can even send data back to a generator function using its `.send()` method. – Ashwini Chaudhary Mar 30 '14 at 09:33

3 Answers3

3

Just another variant, with closures.

def accumulator():
    sum = 0
    def addition(n):
         nonlocal sum
         sum += n
         return sum
    return addition
x3al
  • 586
  • 1
  • 8
  • 24
2

Not sure if this is what you are asking, but you can get the desired effect by updating a class variable.

class accumulator(object):
    summation = 0
    def __call__(self,val):
        accumulator.summation+=val
        print accumulator.summation

A = accumulator()
A(10)
A(10)
B = accumulator()
B(10)
B(100)

This will give:

10
20
30
130

and every instance will have the correct value in the summation attribute.

If you want to keep the summations of A and B separate:

class accumulator(object):
    def __init__(self):
        self.summation = 0
    def __call__(self,val):
        self.summation+=val
        print self.summation
ebarr
  • 7,704
  • 1
  • 29
  • 40
2

You could define a coroutine, as Aशwini चhaudhary suggested:

def coroutine(func):
    """
    http://www.python.org/dev/peps/pep-0342/
    http://www.dabeaz.com/coroutines/index.html
    """
    def wrapper(*args, **kw):
        gen = func(*args, **kw)
        gen.send(None)
        return gen
    return wrapper

@coroutine
def accumulator():
    val = 0
    while True:
        val += (yield val)

which can be used like this:

A = accumulator().send
print(A(10))
# 10

print(A(10))
# 20

print(A(10))
# 30
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677