Skip to content

Commit

Permalink
Interleave optimized. (#325)
Browse files Browse the repository at this point in the history
About 2x faster from minimizing the inner loop.  Also cleaned up exception handling.
  • Loading branch information
coady authored and mrocklin committed Oct 20, 2016
1 parent 13111cd commit c5d6d26
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions toolz/itertoolz.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def _merge_sorted_binary_key(seqs, key):
yield val1


def interleave(seqs, pass_exceptions=()):
def interleave(seqs):
""" Interleave a sequence of sequences
>>> list(interleave([[1, 2], [3, 4]]))
Expand All @@ -227,16 +227,15 @@ def interleave(seqs, pass_exceptions=()):
Returns a lazy iterator
"""
iters = map(iter, seqs)
while iters:
newiters = []
for itr in iters:
try:
iters = itertools.cycle(map(iter, seqs))
while True:
try:
for itr in iters:
yield next(itr)
newiters.append(itr)
except (StopIteration,) + tuple(pass_exceptions):
pass
iters = newiters
return
except StopIteration:
predicate = partial(operator.is_not, itr)
iters = itertools.cycle(itertools.takewhile(predicate, iters))


def unique(seq, key=None):
Expand Down

0 comments on commit c5d6d26

Please sign in to comment.