Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from time import time
- class generators(object):
- """ My collection of useful generator examples in python
- by: Cody Kochmann """
- def started(generator_function):
- """ starts a generator when created """
- def wrapper(*args, **kwargs):
- g = generator_function(*args, **kwargs)
- next(g)
- return g
- return wrapper
- @staticmethod
- @started
- def sum():
- "generator that holds a sum"
- total = 0
- while 1:
- total += yield total
- @staticmethod
- @started
- def counter():
- "generator that holds a sum"
- c = 0
- while 1:
- yield c
- c += 1
- @staticmethod
- @started
- def avg():
- """ generator that holds a rolling average """
- count = 0.0
- total = generators.sum()
- i=0
- while 1:
- i = yield (total.send(i)*1.0/count if count else 0)
- count += 1
- @staticmethod
- @started
- def timer():
- """ generator that tracks time """
- start_time = time()
- previous = start_time
- while 1:
- yield time()-start_time
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement