Search code examples
pythongenerator

I was trying to understand the concept of generators in python I am trying to implement it in different ways but i am getting stuck at one point


For starters I wrote a code for generator to initially grasp the context

def cycleoflife():
    # use yield to create a generator
    for i in range(0, 1000):
        yield "eat"
        yield "sleep"
        yield "code"

which printed

eat
sleep
code

on every next call

But I want to try something different so wanted to implement generator I named Mary such that it shows string like these on every next call:

I love Mary 

Mary love that I love Mary

I love that Mary love that I love Mary

Mary love that I love that Mary love that I love Mary

I love that Mary love that I love that Mary love that I love Mary.....
def Mary():
    for i in range(0, 1000):
        yield "I love Mary"
        yield "Mary love that"
        yield "I love that"

love = Mary()

This is my code I keep getting stuck on how to concatenate my calls in a loop such that I get the above result.


Solution

  • Here's how you could implement this, although this is not really a good use case for a generator. Note that itertools.cycle does exactly what your Mary function was doing.

    from itertools import cycle
    def Mary():
        parts = ["I love Mary", "Mary love that", "I love that"]
        hold = []
        for n in cycle(parts):
            hold.insert( 0, n )
            yield ' '.join(hold)
    
    for s in Mary():
        print(s)