{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# イテレータとジェネレータ" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import sys" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## イテレータ\n", "\n", "自然数$n$が与えられたとき、${}_n C_k$ ($k = 0, 1, \\dots, n$)、および$\\sum_{k=0}^{n} {}_n C_k$を計算するプログラムの例を示す。" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "n = 6" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "6\n", "15\n", "20\n", "15\n", "6\n", "1\n" ] }, { "data": { "text/plain": [ "64" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "v = 1\n", "s = 0\n", "for k in range(n+1):\n", " print(v)\n", " s += v\n", " v *= (n-k)\n", " v //= (k+1)\n", "s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "このプログラムは期待した通りの結果を返すが、for文の反復内容に${}_n C_k$を計算する部分が入るため、見通しが悪い。また、$\\sum_{k=0}^{n} (-1)^k{}_n C_k$を計算するようにプログラムを改変するには、${}_n C_k$を計算する部分も含めて、実装を修正する必要が生じる。見通しのよいプログラムを書くために、range関数が$0, 1, \\dots, n$を返すように、${}_n C_0, {}_n C_1, \\dots, {}_n C_n$を返す関数combinationsを定義し、以下のようなプログラムを書きたい。\n", "```python\n", "s = 0\n", "for v in combinations(n):\n", " print(v)\n", " s += v\n", "s\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "おそらく、真っ先に思い浮かぶのはcombinations関数を${}_n C_k$ ($k = 0, 1, \\dots, n$)のリストを返す関数として実装することであろう(後ほど異なる実装を示すことになるので、ここではcombinationではなくlist_combinationsという名前の関数として実装する)。" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def list_combinations(n):\n", " v = 1\n", " C = []\n", " for k in range(n+1):\n", " C.append(v)\n", " v *= (n-k)\n", " v //= (k+1)\n", " return C" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "list_combinations関数の動作を確認する。" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 6, 15, 20, 15, 6, 1]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list_combinations(n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "このlist_combinations関数を使うと、先ほどの処理を行うプログラムは次のように書ける(呼び出し元のプログラムの見通しは良くなった)。" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "6\n", "15\n", "20\n", "15\n", "6\n", "1\n" ] }, { "data": { "text/plain": [ "64" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 0\n", "for v in list_combinations(n):\n", " print(v)\n", " s += v\n", "s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "また、$\\sum_{k=0}^{n} (-1)^k{}_n C_k$を計算するには、その計算の箇所だけ変更すればよい(動作を分かりやすくするため、`print(k, v)`を入れてある)。" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1\n", "1 6\n", "2 15\n", "3 20\n", "4 15\n", "5 6\n", "6 1\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t = 0\n", "for k, v in enumerate(list_combinations(n)):\n", " print(k, v)\n", " t += ((-1) ** k * v)\n", "t" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "なお、和の計算結果のみが必要であれば、sum関数を用いるだけでよい。" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "64" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(list_combinations(n))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "これにより、見通しのよいプログラムを分かりやすく書くことができたが、一つだけ心残りがある。それは、${}_n C_0, {}_n C_1, \\dots, {}_n C_n$のすべての値を要素とするリストを一時的に作成・保持してしまう点である。今回の目的が$\\sum_{k=0}^{n} {}_n C_k$の値を計算することだけであったら、${}_n C_k$のすべての値をメモリに保持するのは無駄である。なぜなら、${}_n C_k$のすべての値に同時またはランダムにアクセスする必要は無いからである。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "${}_n C_0, {}_n C_1, \\dots, {}_n C_n$のように、要素の値を順に返すような動作を実現してくれる仕組みが[イテレータ](https://docs.python.org/ja/3/glossary.html#term-iterator)である。オブジェクトにイテレータの機能を実装することで、for文の反復対象として用いることができるようになる。オブジェクトにイテレータを実装するには、`__iter__`メソッドと`__next__`メソッドを実装すればよい。`__iter__`メソッドはイテレータオブジェクト自身を返すもので、通常は`self`を返せばよい。`__next__`メソッドには次の要素を返す処理を実装する。これ以上返す要素が無い場合は、[StopIteration](https://docs.python.org/ja/3/library/exceptions.html#StopIteration)例外を送出させる。" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "class iter_combinations:\n", " def __init__(self, n):\n", " self.v = 1\n", " self.k = 0\n", " self.n = n\n", " \n", " def __iter__(self):\n", " return self\n", " \n", " def __next__(self):\n", " if self.n < self.k:\n", " raise StopIteration\n", " v = self.v\n", " self.v *= (self.n - self.k)\n", " self.v //= (self.k+1)\n", " self.k += 1\n", " return v" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "このiter_combinations関数(実際にはクラス)を呼び出すプログラムは、list_combinations関数でリストを予め生成した場合と完全に同じである。" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "6\n", "15\n", "20\n", "15\n", "6\n", "1\n" ] }, { "data": { "text/plain": [ "64" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 0\n", "for v in iter_combinations(n):\n", " print(v)\n", " s += v\n", "s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "なお、和の計算結果のみが必要であれば、list_combinations関数でリストを予め生成した場合と同様に、sum関数を用いるだけでよい。" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "64" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(iter_combinations(n))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$\\sum_{k=0}^{n} (-1)^k{}_n C_k$の計算も同様である。" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1\n", "1 6\n", "2 15\n", "3 20\n", "4 15\n", "5 6\n", "6 1\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t = 0\n", "for k, v in enumerate(iter_combinations(n)):\n", " print(k, v)\n", " t += ((-1) ** k * v)\n", "t" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "当たり前ではあるが、iter_combinationsクラスのオブジェクトはリストではない。" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.iter_combinations at 0x7f07a80aae30>" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "iter_combinations(n)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "__main__.iter_combinations" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(iter_combinations(n))" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(iter_combinations(n), list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "iter_combinationsクラスのイテレータ・オブジェクトから順に要素を取り出すには[next](https://docs.python.org/ja/3/library/functions.html#next)関数を用いる。すべての要素を取り出した後、StopIteration例外が送出されていることが分かる。" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "i = iter_combinations(4)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "tags": [ "raises-exception" ] }, "outputs": [ { "ename": "StopIteration", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_205148/1939748483.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_205148/1028479797.py\u001b[0m in \u001b[0;36m__next__\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m__next__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mn\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mk\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mStopIteration\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 13\u001b[0m \u001b[0mv\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mv\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 14\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mv\u001b[0m \u001b[0;34m*=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mn\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mk\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mStopIteration\u001b[0m: " ] } ], "source": [ "next(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "実際にイテレータ・オブジェクトが消費しているメモリ量を見積もるため、[sys.getsizeof](https://docs.python.org/ja/3/library/sys.html#sys.getsizeof)を用いる。$n=5$のとき、list_combinations関数が生成するオブジェクトよりもiter_combinationsクラスが生成するオブジェクトの方がメモリ消費量が少ない。" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "48" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.getsizeof(iter_combinations(5))" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "120" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.getsizeof(list_combinations(5))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "続いて、$n=100000$とすると、メモリ消費量の差は顕著になる。list_combinations関数が生成するオブジェクトのメモリ消費量は増えていくが、iter_combinationsクラスが生成するオブジェクトのメモリ消費量は$n$によらず一定である。これは、イテレータがすべての要素を持つリストを生成せずに、要素を順番に返す仕様になっているからである。" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "800984" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.getsizeof(list_combinations(100000))" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "48" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.getsizeof(iter_combinations(100000))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ジェネレータ" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "先ほどの${}_n C_k$ ($k = 0, 1, \\dots, n$)を計算する例において、list_combinations関数とiter_combinations関数の実装を再掲する。。" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "6\n", "15\n", "20\n", "15\n", "6\n", "1\n" ] }, { "data": { "text/plain": [ "64" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def list_combinations(n):\n", " v = 1\n", " C = []\n", " for k in range(n+1):\n", " C.append(v)\n", " v *= (n-k)\n", " v //= (k+1)\n", " return C\n", "\n", "class iter_combinations:\n", " def __init__(self, n):\n", " self.v = 1\n", " self.k = 0\n", " self.n = n\n", " \n", " def __iter__(self):\n", " return self\n", " \n", " def __next__(self):\n", " if self.n < self.k:\n", " raise StopIteration\n", " v = self.v\n", " self.v *= (self.n - self.k)\n", " self.v //= (self.k+1)\n", " self.k += 1\n", " return v\n", "\n", "s = 0\n", "#for v in list_combinations(6):\n", "for v in iter_combinations(6):\n", " print(v)\n", " s += v\n", "s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "list_combinations関数とiter_combinationsクラスの実装を比較すると、list_combinations関数の方が見通しがよい。これは、反復処理をfor文で書くことができるため、反復の開始から終了まで、繰り返しの処理内容をまとめて記述できるからである。一方、iter_combinationsクラスにおける`__next__`メソッドでは、現在の状態から次の要素を返す処理を記述することになるため、反復処理全体の流れが分かりにくい。\n", "\n", "この両者の良いところ取りはできないものか? すなわち、list_combinations関数のように反復処理を書くことができ、かつiter_combinationsクラスのようにイテレータとして振る舞う方法は無いだろうか? これを実現するのが、[yield文](https://docs.python.org/ja/3/reference/expressions.html#yieldexpr)によるジェネレータ関数である。関数の中でyield文を記述すると、その関数はジェネレータ関数となる。yield文はreturn文に似ているが、関数の振る舞いをイテレータに変更し、要素を順番に返せるようにするものである。yield文が実行されると、関数の実行は中断し、yield文で指定された値が要素として呼び出し元に返される。言い換えれば、yield文の実行と、イテレータの`__next__`メソッドの返り値が対応する。\n", "\n", "以下のgen_combinations関数は、ジェネレータ関数によるイテレータの実装である。list_combinations関数でリストにappendする代わりに、yield文を実行するプログラムとなる。" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "6\n", "15\n", "20\n", "15\n", "6\n", "1\n" ] }, { "data": { "text/plain": [ "64" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def gen_combinations(n):\n", " v = 1\n", " for k in range(n+1):\n", " yield v\n", " v *= (n-k)\n", " v //= (k+1)\n", "\n", "s = 0\n", "for v in gen_combinations(6):\n", " print(v)\n", " s += v\n", "s" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "64" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(gen_combinations(6))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "yield文を含む関数はジェネレータ関数となる。関数の戻り値はジェネレータ型であり、これはイテレータ・オブジェクトとして用いることができる。" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<generator object gen_combinations at 0x7f07a816a0a0>" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "gen_combinations(4)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "generator" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(gen_combinations(4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ジェネレータ関数の返り値はイテレータとして振る舞うので、[next](https://docs.python.org/ja/3/library/functions.html#next)関数を用いて順に要素を取り出すことができる。すべての要素を取り出した後、StopIteration例外が送出される。" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "i = gen_combinations(4)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(i)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "tags": [ "raises-exception" ] }, "outputs": [ { "ename": "StopIteration", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_205148/1939748483.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mStopIteration\u001b[0m: " ] } ], "source": [ "next(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ジェネレータ式" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "リストの内包表記で$\\{n^2 | n \\in \\{0, 1, 2, 3, 4, 5\\}\\}$をリストとして得る例である。" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 4, 9, 16, 25]" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[n**2 for n in range(6)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "得られたリストに対して、sum関数で和を取ることで、$\\sum_{n=0}^5 n^2$を計算する。" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "55" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum([n**2 for n in range(6)])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`[]`を`()`に変更すると、ジェネレータを内包表記で作成できる(ジェネレータ式)。以下のように関数の唯一の引数として用いる場合は、括弧を二重(`((`や`))`)にしなくてもよい。" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "55" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(i**2 for i in range(6))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ジェネレータ式で$\\sum_{k=0}^{6} (-1)^k{}_6 C_k$を計算する。" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum((-1) ** k * v for k, v in enumerate(iter_combinations(6)))" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "remove-cell" ] }, "source": [ "---\n", "\n", "[Python早見帳](https://chokkan.github.io/python/) © Copyright 2020-2024 by [岡崎 直観 (Naoaki Okazaki)](https://www.chokkan.org/). この作品は<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-nd/4.0/\">クリエイティブ・コモンズ 表示 - 非営利 - 改変禁止 4.0 国際 ライセンス</a>の下に提供されています。<a rel=\"license\" href=\"http://creativecommons.org/licenses/by-nc-nd/4.0/\"><img alt=\"クリエイティブ・コモンズ・ライセンス\" style=\"border-width:0\" src=\"https://i.creativecommons.org/l/by-nc-nd/4.0/80x15.png\" /></a>" ] } ], "metadata": { "@context": { "CreativeWork": "http://schema.org/CreativeWork", "Organization": "http://schema.org/Organization", "Person": "http://schema.org/Person", "author": "http://schema.org/author", "copyrightHolder": "http://schema.org/copyrightHolder", "copyrightYear": "http://schema.org/copyrightYear", "license": "http://schema.org/license", "name": "http://schema.org/name", "title": "http://schema.org/name", "url": "http://schema.org/url" }, "@type": "CreativeWork", "author": [ { "@type": "Person", "name": "Naoaki Okazaki", "url": "https://www.chokkan.org/" } ], "copyrightHolder": [ { "@type": "Person", "name": "Naoaki Okazaki", "url": "https://www.chokkan.org/" } ], "copyrightYear": 2024, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" }, "license": "https://creativecommons.org/licenses/by-nc-nd/4.0/deed.ja", "title": "Python早見帳" }, "nbformat": 4, "nbformat_minor": 4 }