Last active
May 27, 2018 19:38
-
-
Save somacdivad/0319e70e9b2f4745ceb34b48b1a3e8b1 to your computer and use it in GitHub Desktop.
Shuffling an iterator with itertools vs. random.shuffle().
This file contains hidden or 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
import itertools as it | |
import random | |
import timeit | |
def shuffle(deck): | |
"""Return iterator over shuffled deck.""" | |
deck = list(deck) | |
random.shuffle(deck) | |
return iter(tuple(deck)) | |
def ishuffle(iterable, n): | |
"""Return shuffled iterator of an `iterable` with length `n`.""" | |
pool = iter(iterable) | |
for i in range(1, n+1): | |
randn = random.randint(0, n-i) | |
left, right = it.tee(pool, 2) | |
right = it.islice(right, randn, None) | |
yield next(right) | |
pool = it.chain(it.islice(left, randn), right) | |
def test_shuffle(): | |
for _ in shuffle(range(100)): | |
pass | |
print(timeit.timeit('test_shuffle()', | |
setup='from __main__ import test_shuffle', | |
number=10000)) | |
# Output: 1.0292874510050751 | |
def test_ishuffle(): | |
for _ in ishuffle(range(100), 100): | |
pass | |
print(timeit.timeit('test_ishuffle()', | |
setup='from __main__ import test_ishuffle', | |
number=10000)) | |
# Output: 5.076113043993246 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment