Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. from time import time
  2.  
  3. class generators(object):
  4. """ My collection of useful generator examples in python
  5. by: Cody Kochmann """
  6.  
  7. def started(generator_function):
  8. """ starts a generator when created """
  9. def wrapper(*args, **kwargs):
  10. g = generator_function(*args, **kwargs)
  11. next(g)
  12. return g
  13. return wrapper
  14.  
  15. @staticmethod
  16. @started
  17. def sum():
  18. "generator that holds a sum"
  19. total = 0
  20. while 1:
  21. total += yield total
  22.  
  23. @staticmethod
  24. @started
  25. def counter():
  26. "generator that holds a sum"
  27. c = 0
  28. while 1:
  29. yield c
  30. c += 1
  31.  
  32. @staticmethod
  33. @started
  34. def avg():
  35. """ generator that holds a rolling average """
  36. count = 0.0
  37. total = generators.sum()
  38. i=0
  39. while 1:
  40. i = yield (total.send(i)*1.0/count if count else 0)
  41. count += 1
  42.  
  43. @staticmethod
  44. @started
  45. def timer():
  46. """ generator that tracks time """
  47. start_time = time()
  48. previous = start_time
  49. while 1:
  50. yield time()-start_time
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement