M.Hiroi's Home Page

Python3 Programming

お気楽 Python3 プログラミング超入門

Copyright (C) 2022-2026 Makoto Hiroi
All rights reserved.

●ジェネレータ (2)

>>> def foo():
...     a = yield "foo"
...     print("foo: ", a)
...     b = yield "bar"
...     print("foo: ", b)
...     c = yield "baz"
...     print("foo: ", c)
...
>>> g = foo()
>>> print(g.send(None))
foo
>>> print(g.send("foo1"))
foo:  foo1
bar
>>> print(g.send("foo2"))
foo:  foo2
baz
>>> print(g.send("foo3"))
foo:  foo3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

>>> for x in foo(): print(x)
...
foo
foo:  None
bar
foo:  None
baz
foo:  None
リスト : 複数のコルーチンを呼び出す

def make_coroutine(code):
    while True:
        print(code, end="")
        yield None

def test1(n):
    a = make_coroutine("h")
    b = make_coroutine("e")
    c = make_coroutine("y")
    d = make_coroutine("!")
    e = make_coroutine(" ")
    for _ in range(n):
        for g in [a, b, c, d, e]: next(g)
    for g in [a, b, c, d, e]: g.close()
>>> test1(5)
hey! hey! hey! hey! hey! >>>
>>> test1(10)
hey! hey! hey! hey! hey! hey! hey! hey! hey! hey! >>>
リスト : 子コルーチンから子コルーチンを呼び出す

def make_coroutine2(code, g):
    while True:
        print(code, end="")
        if g: next(g)
        yield None

def test2(n):
    e = make_coroutine2(" ", None)
    d = make_coroutine2("!", e)
    c = make_coroutine2("y", d)
    b = make_coroutine2("e", c)
    a = make_coroutine2("h", b)
    for _ in range(n): next(a)
    for g in [a, b, c, d, e]: g.close()
>>> test2(5)
hey! hey! hey! hey! hey! >>>
>>> test2(15)
hey! hey! hey! hey! hey! hey! hey! hey! hey! hey! hey! hey! hey! hey! hey!
リスト : エラトステネスの篩

# n から始まる整数列
def integers(n):
    while True:
        yield n
        n += 1

# フィルター
def stream_filter(pred, s):
    while True:
        x = next(s)
        if pred(x): yield x

# n 個の素数を求める
def sieve(n):
    # 変数 x の値をクロージャ内に保持する
    def make_pred(x):
        return lambda y: y % x != 0
    #
    nums = integers(2)
    ps = []
    for _ in range(n):
        x = next(nums)
        ps.append(x)
        nums = stream_filter(make_pred(x), nums)
    return ps

# 再帰にすると lambda だけでも動作する
def sieve1(n, nums, ps):
    if n == 0:
        return ps
    else:
        x = next(nums)
        ps.append(x)
        return sieve1(n - 1, stream_filter(lambda y: y % x != 0, nums), ps)
>>> sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
 83, 89, 97]
>>> sieve(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167,
 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367,
 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]

>>> sieve1(25, integers(2), [])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
 83, 89, 97]
>>> sieve1(100, integers(2), [])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 
 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263,
 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367,
 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
リスト :  簡単なマルチプロセス

# 中断中のプロセスを格納するキュー
proc_queue = []

# キューに追加
def enqueue(x):
    proc_queue.append(x)

# キューからデータを取り出す
def dequeue():
    x = proc_queue[0]
    del proc_queue[0]
    return x

# キューは空か?
def isempty():
    return len(proc_queue) == 0

# プロセスの生成
def fork(fn):
    g = fn()
    g.send(None)
    proc_queue.append(g)

# メインプロセス
def main_process(*args):
    # プロセスの登録
    for fn in args: fork(fn)
    # 実行
    while not isempty():
        p = dequeue()
        if p.send(False):
            enqueue(p)
        else:
            p.close()

# 子プロセス
def mtest0(name, n):
    while n > 0:
        print(name, n)
        yield True
        n -= 1
    yield False
>>> main_process(lambda : mtest0("foo", 5), lambda : mtest0("bar", 7))
foo 5
bar 7
foo 4
bar 6
foo 3
bar 5
foo 2
bar 4
foo 1
bar 3
bar 2
bar 1
>>> main_process(lambda : mtest0("foo", 5), lambda : mtest0("bar", 7),
 lambda : mtest0("oops", 6))
foo 5
bar 7
oops 6
foo 4
bar 6
oops 5
foo 3
bar 5
oops 4
foo 2
bar 4
oops 3
foo 1
bar 3
oops 2
bar 2
oops 1
bar 1

初版 2024 年 4 月 28 日

●asyncio

●非同期ジェネレータ


初版 2024 年 5 月 3, 5 日

●仮想環境とパッケージ


初版 2026 年 2 月 2 日