[Edu-sig] Prime Numbers...

kirby urner kirby.urner at gmail.com
Sun Feb 19 12:00:05 EST 2017


Heres's a fix for the coroutine-based primes generator.  It was trying to
open a file that still wasn't closed, so would not print anything on first
run (run it again, and the file from last time would print).  I need to
close that file at the end.  The fix looks a bit inelegant, sending a -1
into the printer loop coroutine, triggering a StopIteration, which I
catch.  It should work now at least.  Thanks to my buddy off list for
testing it.

# -*- coding: utf-8 -*-
"""
Created on Thu Oct 13 13:48:52 2016

@author: Kirby Urner

David Beazley:
https://youtu.be/Z_OAlIhXziw?t=23m42s

Trial by division, but this time the primes coroutine acts
more as a filter, passing qualified candidates through to
print_me, which writes to a file.
"""

def coroutine(func):
    """
    Advances decorated generator function to the first yield
    """
    def start(*args, **kwargs):
        cr = func(*args, **kwargs)
        cr.send(None)  # or next(cr) or cr.__next__()
        return cr
    return start

@coroutine
def print_me(file_name):
    with open(file_name, 'w') as file_obj:
        while True:
            to_print = (yield)
            if to_print == -1:
                break
            file_obj.write(str(to_print)+"\n")
    # print("File closed")

@coroutine
def primes(target):
    _primes_so_far = [2]
    while True:
        candidate = (yield)
        for prev in _primes_so_far:
            if not divmod(candidate, prev)[1]:
                break
            if prev**2 > candidate:
                _primes_so_far.append(candidate)
                target.send(candidate)
                break

output = print_me("primes.txt")
p = primes(output)

for x in range(3, 200, 2):  # test odds 3-199
    p.send(x)

try:
    output.send(-1)  # tell print_me coroutine to quit, close file
except:
    pass

with open("primes.txt", 'r') as file_obj:
    print(file_obj.read())
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20170219/f29e4d66/attachment.html>


More information about the Edu-sig mailing list