multirember&co

Anton Vredegoor anton.vredegoor at gmail.com
Thu Apr 19 18:37:46 EDT 2007


Anton Vredegoor wrote:

> Maybe this one is better?

No, this one keeps generating output.

But this one stops at least:

from collections import deque
from itertools import chain, repeat

def xsplitter(seq, pred):
     Q = deque(),deque()
     sentinel = object()
     it = chain(seq,repeat(sentinel))
     def gen(p):
         for x in it:
             if x is sentinel:
                 while Q[p]:  yield Q[p].popleft()
                 break
             elif pred(x) == p:
                 while Q[p]:  yield Q[p].popleft()
                 yield x
             else:
                 Q[~p].append(x)
                 for x in gen(p):  yield x
     return gen(1),gen(0)

def test():
     L = 1, 2, 3, 'a', 'a'
#    L = 'a', 1, 2, 'a'
#    L = 1, 'a', 3, 'a', 4, 5, 6, 'a'
     it1, it2 = xsplitter(L, lambda x: x == 'a')
     print it1.next()
     print it2.next()
     print it1.next()
     print it2.next()

if __name__=='__main__':
     test()

Are there any other cases this doesn't cover?

A.



More information about the Python-list mailing list