Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Last active October 28, 2018 17:35
Show Gist options
  • Save vlad-bezden/59cda749fbf994c9d61cf90f36be7cb1 to your computer and use it in GitHub Desktop.
Save vlad-bezden/59cda749fbf994c9d61cf90f36be7cb1 to your computer and use it in GitHub Desktop.
Function example of pair/legs of iterable. The type variable, T_, created with the TypeVar function, is used to clarify precisely how the legs() function restructures the data. The hint says that the input type is preserved on output. The input type is an Iterator of some arbitrary type, T_; the output will include tuples of the same type, T_. N…
from typing import Iterator, Any, Iterable, TypeVar, Tuple
T_ = TypeVar('T_')
Pairs_Iter = Iterator[Tuple[T_, T_]]
def legs(iterable: Iterator[T_]) -> Pairs_Iter:
begin = next(iterable)
for end in iterable:
yield begin, end
begin = end
@vlad-bezden
Copy link
Author

vlad-bezden commented Oct 28, 2018

Usage:

list(legs(x for x in range(3)))
# [(0, 1), (1, 2)]

list(legs(iter([0, 1, 2])))
# [(0, 1), (1, 2)]

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