Skip to content

Instantly share code, notes, and snippets.

@bixb0012
Last active July 30, 2019 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bixb0012/5d57bf95290babd9e60eae0aca1f9e0a to your computer and use it in GitHub Desktop.
Save bixb0012/5d57bf95290babd9e60eae0aca1f9e0a to your computer and use it in GitHub Desktop.
Python: Lazy Counters
#!python
# Reference: 1) https://docs.python.org/3/library/collections.html#collections.defaultdict
# Reference: 2) https://www.python.org/dev/peps/pep-0342/
from collections import defaultdict
# Example 1: Using coroutine via generator for multivalue counter
def multi_counter_generator():
cnt = defaultdict(int)
incr = yield cnt.items()
while True:
if incr is None:
for k in cnt.keys():
cnt[k] += 1
incr = yield cnt.items()
else:
if not isinstance(incr, (list, tuple)):
cnt[incr] += 1
incr = yield cnt[incr]
else:
for i in incr:
cnt[i] += 1
incr = yield [(i,cnt[i]) for i in incr]
# Example 2: Using coroutine via generator for counter with dynamic increments
def counter_generator(start=0):
cnt = start
incr = yield cnt
while True:
if incr is None:
cnt += 1
else:
cnt += incr
incr = yield cnt
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment