Guest User

Untitled

a guest
Oct 17th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. """Randomly interleave iterables while preserving their order.
  2.  
  3. Defines a Python 2.7 function "interleave" that returns an iterator
  4. that randomly interleaves each of its iterables while preserving
  5. their order. For example, one possible result of
  6.  
  7. list(interleave(xrange(1, 6), xrange(6, 11)))
  8.  
  9. is:
  10.  
  11. [6, 7, 8, 1, 2, 9, 3, 10, 4, 5]
  12.  
  13. Example:
  14.  
  15. >>> result = list(interleave(range(1, 6), range(6, 11), range(11, 16)))
  16. >>>
  17. >>> # The result contains all the elements of the iterables
  18. >>> len(result)
  19. 15
  20. >>> sorted(result)
  21. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  22. >>>
  23. >>> # The order of the iterables is preserved
  24. >>> i = [r for r in result if r >= 1 and r < 6]
  25. >>> j = [r for r in result if r >= 6 and r < 11]
  26. >>> k = [r for r in result if r >= 11 and r < 16]
  27. >>> i == range(1, 6)
  28. True
  29. >>> j == range(6, 11)
  30. True
  31. >>> k == range(11, 16)
  32. True
  33. """
  34. import itertools
  35. import random
  36.  
  37. def interleave(*iterables):
  38. """Return an iterator that randomly interleaves the iterable arguments."""
  39. args = (i if hasattr(i, "__len__") else list(i) for i in iterables)
  40. iters = sum(([iter(a)]*len(a) for a in args), [])
  41. random.shuffle(iters)
  42. return itertools.imap(next, iters)
Add Comment
Please, Sign In to add comment