Last active
July 30, 2019 23:45
-
-
Save bixb0012/5d57bf95290babd9e60eae0aca1f9e0a to your computer and use it in GitHub Desktop.
Python: Lazy Counters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!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