Skip to content

Instantly share code, notes, and snippets.

@zeehio
Created October 15, 2017 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeehio/cdf7d881cc7f612b2c853fbd3a18ccbe to your computer and use it in GitHub Desktop.
Save zeehio/cdf7d881cc7f612b2c853fbd3a18ccbe to your computer and use it in GitHub Desktop.
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