"""Code for examples from lecture 35""" # Basic coroutine: match a pattern def match(pattern): print("Looking for %s" % pattern) try: while True: line = (yield) if pattern in line: print(line) except GeneratorExit as e: print("Done.") def read(text, next_coroutine): for word in text.split(): next_coroutine.send(word) next_coroutine.close() # Example text = "Commending spending is offending to people pending lending!" matcher = match("ending") matcher.__next__() read(text, matcher) # More advanced -- counting the most frequent letter def count_letters(next_coroutine): try: while True: line = (yield) counts = {} for letter in line: if letter != " ": if letter in counts: counts[letter] += 1 else: counts[letter] = 1 next_coroutine.send(counts) except GeneratorExit as e: next_coroutine.close() def sum_dictionaries(): aggregated = {} try: while True: dictionary = (yield) for key in dictionary.keys(): if key not in aggregated: aggregated[key] = dictionary[key] else: aggregated[key] += dictionary[key] except GeneratorExit as e: max_key = None max_value = -1 for key in aggregated.keys(): if aggregated[key] > max_value: max_key = key max_value = aggregated[key] print("Most frequent key: "+str(max_key)) s = sum_dictionaries() s.__next__() c = count_letters(s) c.__next__() r = read(text, c) # Multitasking def read_to_many(text, coroutines): for word in text.split(): for coroutine in coroutines: coroutine.send(word) for coroutine in coroutines: coroutine.close() def match_filter(pattern, next_coroutine): print('Looking for ' + pattern) try: while True: s = (yield) if pattern in s: next_coroutine.send(s) except GeneratorExit: next_coroutine.close() def print_consumer(): print('Preparing to print') try: while True: line = (yield) print(line) except GeneratorExit: print("Done.") # Example printer = print_consumer() printer.__next__() m = match_filter("mend", printer) m.__next__() p = match_filter("pe", printer) p.__next__() read_to_many(text, [m, p])