Last active
February 21, 2019 19:21
-
-
Save dsh0005/390af82066b81b1650a3c2c42dfab268 to your computer and use it in GitHub Desktop.
Boustrophedonic python itertool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# encoding=utf-8 | |
# vim: set nobomb: | |
from itertools import chain, cycle, repeat | |
from typing import Iterable, Iterator, Reversible, TypeVar | |
T = TypeVar('T') | |
def boustrophedon(iterator: Iterator[Reversible[T]])\ | |
-> Iterator[Reversible[T]]: | |
""" | |
Takes an iterator of (reversible) iterators, returns the | |
first element, then returns the second element reversed, | |
then the third, then the fourth reversed, and so on. | |
""" | |
xforms = cycle([lambda it: it, reversed]) | |
for xform, elem in zip(xforms, iterator): | |
yield xform(elem) | |
def boustrophedon_chained(iterator: Reversible[T], times: int=None)\ | |
-> Iterable[T]: | |
""" | |
Used much like itertools.repeat, except it reverses every other | |
repetition, and it's chained. | |
""" | |
if times is None: | |
while True: | |
yield iterator | |
yield reversed(iterator) | |
else: | |
for i, reverse in zip(range(times), chain.from_iterable(repeat([False, True]))): | |
yield reversed(iterator) if reverse else iterator | |
__all__ = ["boustrophedon", "boustrophedon_chained"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line #22
Oops, can you tell I don't use
repeat
much?