"Implement this protocol in classes which can act as generators. The ubiquitous [range](https://docs.python.org/3/library/stdtypes.html#ranges) class is a great example of an iterator. (In older versions of python range returned a list which itself was enumerated; this is costly in terms of memory.)\n",

"text": "1 = 1\n2 = 2\n3 = 3\n4 = 5\n5 = 8\n3 is a member of the sequence? True\n4 is a member of the sequence? False\nThe first 7 terms of the sequence: [1, 2, 3, 5, 8, 13, 21]\n"

}

],

"source": [

"class FibonacciGenerator:\n",

" \"\"\" Implements the Iteration protocol to generate the Fibonacci sequence \"\"\"\n",

" def __init__(self, max_iterations=100):\n",

" self._max_iterations = max_iterations\n",

"\n",

" def __iter__(self):\n",

" self._a = 0\n",

" self._b = 1\n",

" self._iteration = 0\n",

" return self\n",

"\n",

" def __next__(self):\n",

" self._iteration += 1\n",

" if self._iteration > self._max_iterations:\n",

" raise StopIteration()\n",

" result = self._a + self._b\n",

" self._a = self._b\n",

" self._b = result\n",

" return result\n",

"\n",

"for iteration, result in enumerate(FibonacciGenerator(max_iterations=5)):\n",

" print(f'{iteration + 1} = {result}')\n",

"\n",

"print(f'3 is a member of the sequence? {3 in FibonacciGenerator()}')\n",

"print(f'4 is a member of the sequence? {4 in FibonacciGenerator()}')\n",

"print(f'The first 7 terms of the sequence: {list(FibonacciGenerator(max_iterations=7))}')"