This is really nice, but I think you have a negation wrong in there
somewhere:

In [1]: from collections import deque
   ...:
   ...: def partition(pred, iterable):
   ...:     results = deque([]), deque([])
   ...:
   ...:     def gen_split(only):
   ...:         for thing in iterable:
   ...:             if results[only]:
   ...:                 yield results[only].popleft()
   ...:             results[not pred(thing)].append(thing)
   ...:         for thing in results[only]:
   ...:             yield thing
   ...:
   ...:     return gen_split(True), gen_split(False)
   ...:

In [2]: def isEven(n):
   ...:     return n/2 == n//2
   ...:

In [3]: from itertools import count

In [4]: evens, odds = partition(isEven, count())

In [5]: next(evens)
Out[5]: 1

In [6]: next(evens)
Out[6]: 3

In [7]: next(evens)
Out[7]: 5

In [8]: next(odds)
Out[8]: 0

In [9]: next(odds)
Out[9]: 2

In [10]: next(odds)
Out[10]: 4

On Mon, Jun 6, 2022 at 10:32 AM Mathew Elman <mathew.el...@ocado.com> wrote:

> from collections import deque
>
> def partition(pred, iterable):
>     results = deque([]), deque([])
>
>     def gen_split(only):
>         for thing in iterable:
>             if results[only]:
>                 yield results[only].popleft()
>             results[not pred(thing)].append(thing)
>         for thing in results[only]:
>             yield thing
>
>     return gen_split(True), gen_split(False)
> _______________________________________________
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/EUAYPXMZM4DOGTAAUURNOMWTDU65K6UY/
> Code of Conduct: http://python.org/psf/codeofconduct/
>


-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/HWKJMLZSQVZQERYAKYZUAMK2YGIFUPIX/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to