multirember&co

Anton Vredegoor anton.vredegoor at gmail.com
Fri Apr 20 00:09:28 CEST 2007


attn.steven.kuo at gmail.com wrote:

> Um, no.  That one stops prematurely if
> your input sequence is:
> 
> L = 1, 2, 3, 'a', 'a'

Ah, thanks!

> You get points for persistence, however.  :)

Maybe this one is better?

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  pred(x) != p and x is not sentinel:
                 Q[~p].append(x)
                 for x in gen(p):  yield x
             else:
                 while Q[p]:  yield Q[p].popleft()
             if pred(x) == p: yield x
             else: break
     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()

A.



More information about the Python-list mailing list