Skip to content

Instantly share code, notes, and snippets.

@dsh0005
Last active February 21, 2019 19:21
Show Gist options
  • Save dsh0005/390af82066b81b1650a3c2c42dfab268 to your computer and use it in GitHub Desktop.
Save dsh0005/390af82066b81b1650a3c2c42dfab268 to your computer and use it in GitHub Desktop.
Boustrophedonic python itertool
#!/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"]
@dsh0005
Copy link
Author

dsh0005 commented Aug 21, 2018

line #22
Oops, can you tell I don't use repeat much?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment