0

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.

S.B
  • 13,077
  • 10
  • 22
  • 49
  • Each `yield` yields one thing. If you want to do a reverse concatenate on the results, you'd do that in the function that CALLS `Mary`. – Tim Roberts Oct 21 '22 at 17:07
  • Does this answer your question? [What does the "yield" keyword do?](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do) – rafathasan Oct 21 '22 at 17:18

1 Answers1

3

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)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • I guess the reason you said that this is not a good use case is because you could just return the `hold` list instead of yielding each value, thereby making the use of `yield` unnecessary? – M B Oct 21 '22 at 17:41
  • Well, this is a fuzzy philosophical point. The point of using a generator is that it should have to retain all that state. It should just be generating the phrases. It should be up to the user/caller to decide how to combine the results of the generator. – Tim Roberts Oct 21 '22 at 18:57
  • This is great i know cycle does the same but challenge was for using generator by the way i was told to do the same thing but now with changing capetalization like I love you You love that I love you I love that you love that I love you here you can see the capitalization changes i tried to use the capitalize function but it didn't work – Dani_lucifer923 Oct 22 '22 at 18:46
  • You would leave it lower case ("you") in your list, and then always uppercase the first letter of your response. If it's already capital ("I", "Mary") it won't matter. – Tim Roberts Oct 22 '22 at 19:22