Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if the value is ONE-BUT-LAST in a Python generator?

Since generator returns values lazily, how do I determine if the value returned from a generator is one-but-last? I spent like an hour on this and can't figure it out.

Any help appreciated. Is it even possible??

Thanks, Boda Cydo!

like image 324
bodacydo Avatar asked Dec 02 '25 11:12

bodacydo


1 Answers

You can wrap the generator in a generator that generates a sequence of pairs whose first element is a boolean telling you whether the element is the last-but-one:

def ending(generator):
    z2 = generator.next()
    z1 = generator.next()
    for x in generator:
        yield (False, z2)
        z2, z1 = z1, x
    yield (True, z2)
    yield (False, z1)

Let's test it on a simple iterator:

>>> g = iter('abcd')
>>> g
<iterator object at 0x9925b0>

You should get:

>>> for is_last_but_one, char in ending(g):
...     if is_last_but_one:
...         print "The last but one is", char
... 
The last but one is c

Too see what's happening under the hood:

>>> g = iter('abcd')
>>> for x in ending(g):
...     print x
... 
(False, 'a')
(False, 'b')
(True, 'c')
(False, 'd')
like image 165
krawyoti Avatar answered Dec 04 '25 23:12

krawyoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!