Commit c684ff66 authored by Jon Shadforth's avatar Jon Shadforth
Browse files

Added playground for miscellanous noodles

parent 7c3fad8a
{
"nbformat": 4,
"nbformat_minor": 2,
"metadata": {
"language_info": {
"name": "python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"version": "3.8.0-final"
},
"orig_nbformat": 2,
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"npconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": 3,
"kernelspec": {
"name": "python38064bitbc551774f43d49c287181293c63f83ce",
"display_name": "Python 3.8.0 64-bit"
}
},
"cells": [
{
"cell_type": "markdown",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"### Iterator protocol\n",
"\n",
"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",
"\n",
"[Python docs](https://docs.python.org/3/library/stdtypes.html#iterator-types)\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"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))}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
]
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment