1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

再帰関数でyieldを利用したい

Posted at

はじめに

再帰関数でyieldを利用したい場合はyield fromを利用します。

例題

以下のような仮想的なディレクトリ構造をリストで表現し、それを再帰的に探索するジェネレーターを作ってみましょう。

tree: list[tuple[str, str]] = [
    ("root", "folder1"),
    ("root", "folder2"),
    ("root", "file4.txt"),
    ("folder1", "file1.txt"),
    ("folder1", "file2.txt"),
    ("folder2", "folder3"),
    ("folder3", "file3.txt"),
]

yield from を使った再帰ジェネレーター

def walk(
    tree: list[tuple[str, str]], stack: list[str], current: str
) -> Iterator[list[str]]:
    if current.endswith(".txt"):
        yield stack

    for parent, child in tree:
        if parent == current:
            stack.append(child)
            yield from walk(tree, stack, child)
            stack.pop()

この walk 関数は、ディレクトリ構造を再帰的にたどりながら、ファイルのパスを1つずつジェネレートします。

実行例

for path in walk(tree, ["root"], "root"):
    print(path)

出力例:

['root', 'folder1', 'file1.txt']
['root', 'folder1', 'file2.txt']
['root', 'folder2', 'folder3', 'file3.txt']
['root', 'file4.txt']

関連リンク

実行環境

  • Python 3.13.7
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?