Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Randomly interleave iterables while preserving their order.
- Defines a Python 2.7 function "interleave" that returns an iterator
- that randomly interleaves each of its iterables while preserving
- their order. For example, one possible result of
- list(interleave(xrange(1, 6), xrange(6, 11)))
- is:
- [6, 7, 8, 1, 2, 9, 3, 10, 4, 5]
- Example:
- >>> result = list(interleave(range(1, 6), range(6, 11), range(11, 16)))
- >>>
- >>> # The result contains all the elements of the iterables
- >>> len(result)
- 15
- >>> sorted(result)
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
- >>>
- >>> # The order of the iterables is preserved
- >>> i = [r for r in result if r >= 1 and r < 6]
- >>> j = [r for r in result if r >= 6 and r < 11]
- >>> k = [r for r in result if r >= 11 and r < 16]
- >>> i == range(1, 6)
- True
- >>> j == range(6, 11)
- True
- >>> k == range(11, 16)
- True
- """
- import itertools
- import random
- def interleave(*iterables):
- """Return an iterator that randomly interleaves the iterable arguments."""
- args = (i if hasattr(i, "__len__") else list(i) for i in iterables)
- iters = sum(([iter(a)]*len(a) for a in args), [])
- random.shuffle(iters)
- return itertools.imap(next, iters)
Add Comment
Please, Sign In to add comment