multirember&co

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Wed Apr 18 15:50:57 EDT 2007


On Apr 18, 12:23 pm, Anton Vredegoor <anton.vredeg... at gmail.com>
wrote:

(snipped)

> But still, the 'while True:' loop and the 'try-except' clause and the
> explicit StopIteration are not necessary ...
>
> from collections import deque
>
> def xsplitter(seq, pred):
>      Q = deque(),deque()
>      it = iter(seq)
>      def gen(p):
>          while Q[p]:  yield Q[p].popleft()
>          for x in it:
>              if pred(x) == p: yield x
>              else:
>                  Q[~p].append(x)
>                  for x in gen(p):  yield x
>      return gen(1),gen(0)
>
> def test():
>      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()
>
> if __name__=='__main__':
>      test()
>
> A.



Try it with

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


The last print statement raises StopIteration...
We, however, expected each iterator to contain
two elements (one yielding 'a' then 'a', and
the other yielding 1 then 2).

--
Regards,
Steven




More information about the Python-list mailing list