edocx
edocx

Reputation: 97

Histogram problem using Python generator?

I am new to generators and coroutines. Am trying to mimic the common histogram problem (given a list, return the occurences of each element in that list) using generators.

def genFunc():
    dct = {}
    while True:
        num = yield
        if num not in dct.keys():
            dct[num]=1
        else:
            dct[num]+=1
        print dct


g = genFunc()
next(g)

for each in [1,1,1,2]:
    print g.send(each)

With the code above, I am able to print out the state of dictionary "dct" at each stage. How do I return it to the calling func? If I use a return outside of the while block, I get error - cannot use return with yield.

As I understand, the value passed in send is received by the generator at the yield statement. In this case ideally I would want to pass a number/integer and get back the current state of the dict.

Upvotes: 1

Views: 120

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45750

yield "returns" the data back. You're using it to receive data from the caller, but it can also be used to send data:

def genFunc():
    dct = {}
    while True:
        num = yield dct  # I'm yielding the dictionary
        if num not in dct.keys():
            dct[num] = 1

        else:
            dct[num] += 1


g = genFunc()
next(g)

for each in [1, 1, 1, 2]:
    print g.send(each)

{1: 1}
{1: 2}
{1: 3}
{1: 3, 2: 1}

send returns what was yielded.

Upvotes: 2

Related Questions