Last active
August 25, 2018 22:46
-
-
Save dbramucci/7b1fbc360b6aba0362ba500763585132 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
from timeit import timeit | |
a = list(range(6)) | |
num = 1_000_000 | |
print("toons's: ", timeit(""" | |
i = iter(islice(iter(a), 0, len(a), 2)) | |
j = iter(islice(iter(a), 1, len(a), 2)) | |
try: | |
while True: | |
# print("({} {})".format()) | |
next(i) | |
next(j) | |
except StopIteration: pass | |
""", setup=""" | |
from itertools import islice""", | |
number=num, globals=globals()), "seconds for", num, "runs") | |
print("cylonoven's: ", timeit(""" | |
l = len(a) | |
[(x,a[i+1]if i+1<l else None) for i,x in enumerate(a) if i%2] | |
""", | |
number=num, globals=globals()), "seconds for", num, "runs") | |
print("toon's using for loops", timeit(""" | |
evens = islice(a, 0, len(a), 2) | |
odds = islice(a, 1, len(a), 2) | |
for even, odd in zip(evens, odds): | |
# print("({} {})".format(even, odd)) | |
even | |
odd | |
""", setup=""" | |
from itertools import islice""", | |
number=num, globals=globals()), "seconds for", num, "runs") | |
def in_pairs(iterable): | |
iterator = iter(iterable) | |
try: | |
while True: | |
first = next(iterator) | |
second = next(iterator) | |
yield (first, second) | |
# I believe this is required for python >= 3.7 | |
except StopIteration as e: | |
raise e | |
print("dbramucci's general generator solution: ", timeit(""" | |
for even, odd in in_pairs(a): | |
even | |
odd | |
""", number=num, globals=globals()), "seconds for", num, "runs") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment