>>g = delayed_g...">

Can I simplify this "delayed" python generator?

I want the generator to return what I sent to it in the following iteration:

>>>g = delayed_generator()
>>>g.send(None)

>>>g.send('this')

>>>g.send('is')
'this'
>>>g.send('delayed')
'is'
>>>g.send('!')
'delayed'

I came up with a solution that includes three internal variables, and I am wondering if there is an easier way to do this. This is my decision:

def delayed_generator():
    y = None
    z = None
    while True:
        x = yield y
        y=x
        y = yield z
        z=y
        z = yield x
        x=z
+4
source share
1 answer

You can save the queue:

def delayed_generator():
     q = [None, None]
     while True:
         x = yield q.pop(0)
         q.append(x)

g = delayed_generator()
g.send(None), g.send('this'), g.send('is'), g.send('delayed'), g.send('!')

returns

(None, None, 'this', 'is', 'delayed')
+3
source

Source: https://habr.com/ru/post/1692487/


All Articles