Created
October 15, 2017 10:55
-
-
Save zeehio/cdf7d881cc7f612b2c853fbd3a18ccbe to your computer and use it in GitHub Desktop.
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
setup1 = """ | |
from itertools import zip_longest | |
def zip_equal(*iterables): | |
sentinel = object() | |
for combo in zip_longest(*iterables, fillvalue=sentinel): | |
if sentinel in combo: | |
raise ValueError('Iterables have different lengths') | |
yield combo | |
a = range(100) | |
b = range(100) | |
""" | |
setup2 = """ | |
import itertools | |
class _SentinelException(Exception): | |
def __iter__(self): | |
raise _SentinelException | |
def zip_equal(iterable1, iterable2): | |
i1 = iter(itertools.chain(iterable1, _SentinelException())) | |
i2 = iter(iterable2) | |
try: | |
while True: | |
yield (next(i1), next(i2)) | |
except _SentinelException: # i1 reaches end | |
try: | |
next(i2) # check whether i2 reaches end | |
except StopIteration: | |
pass | |
else: | |
raise ValueError('the second iterable is longer than the first one') | |
except StopIteration: # i2 reaches end, as next(i1) has already been called, i1's length is bigger than i2 | |
raise ValueError('the first iterable is longger the second one.') | |
a = range(100) | |
b = range(100) | |
""" | |
import timeit | |
print(timeit.timeit('list(zip_equal(a, b))', setup1, number=100000)) # 1.55 | |
print(timeit.timeit('list(zip_equal(a, b))', setup2, number=100000)) # 2.83 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment