Guest User

Untitled

a guest
Jun 21st, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import sys
  2. # requires Python 2.5
  3. assert sys.version_info[1] >= 5, "Requires Python Coroutines. See PEP 0342"
  4.  
  5. def pushbackiter(iterator):
  6. """converts 'iterator' into a coroutine, with limited pushback
  7.  
  8. >>> it = pushbackiter([1,2,3,4,5])
  9. >>> it.next()
  10. 1
  11. >>> it.send(1)
  12. None
  13. >>> it.next()
  14. 1
  15. """
  16. for elem in iterator:
  17. pushback = yield elem # yield 'elem' to the caller of '.next()', 'pushback' will become == 'None'
  18. if pushback is not None: # this implementation is unable to take back a None value
  19. yield None # yield 'None' to the caller of '.send(x)'
  20. pushback = yield pushback # sets 'pushback' to the value passed in via '.send(x)'
  21.  
  22. def intervals(xs):
  23. """groups 'xs' into a pair generator indicating consecutive ranges
  24.  
  25. >>> list(intervals([1,2,3,5,7,8,12,15,16])
  26. [(1,3),(5,),(7,8),(12,),(15,16)]
  27. """
  28. def peek(xs):
  29. """helper function does the pushback for us"""
  30. x = xs.next()
  31. xs.send(x)
  32. return x
  33.  
  34. xs = pushbackiter(xs)
  35. for x in xs:
  36. x_ = x
  37. while True: # locate the last successor of x
  38. try:
  39. y = peek(xs)
  40. if x_ + 1 == y:
  41. x_ = y
  42. y = xs.next()
  43. continue
  44. elif x_ == x: # x_ + 1 is not a successor and we have not iterated off the left bound
  45. x_ = None
  46. except StopIteration:
  47. x_ = None
  48.  
  49. break
  50.  
  51. if x_ is not None:
  52. yield (x, x_)
  53. else:
  54. yield (x,)
Add Comment
Please, Sign In to add comment