mirror of
https://github.com/donnemartin/data-science-ipython-notebooks.git
synced 2024-03-22 13:30:56 +08:00
Added snippet for generators.
This commit is contained in:
parent
900b493e54
commit
97c7118117
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"metadata": {
|
"metadata": {
|
||||||
"name": "",
|
"name": "",
|
||||||
"signature": "sha256:1123ef3475d906de39c34c42c18ebeda8c0f1c60ee01b6e692125a51b325d8e7"
|
"signature": "sha256:a81c81558508aed1c6f336342652e5f8dcc250ecd9f9f955b9e6e02d65a45c5c"
|
||||||
},
|
},
|
||||||
"nbformat": 3,
|
"nbformat": 3,
|
||||||
"nbformat_minor": 0,
|
"nbformat_minor": 0,
|
||||||
|
@ -394,13 +394,13 @@
|
||||||
{
|
{
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"output_type": "pyout",
|
"output_type": "pyout",
|
||||||
"prompt_number": 18,
|
"prompt_number": 8,
|
||||||
"text": [
|
"text": [
|
||||||
"10"
|
"10"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"prompt_number": 18
|
"prompt_number": 8
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
|
@ -423,13 +423,61 @@
|
||||||
{
|
{
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"output_type": "pyout",
|
"output_type": "pyout",
|
||||||
"prompt_number": 19,
|
"prompt_number": 9,
|
||||||
"text": [
|
"text": [
|
||||||
"7"
|
"7"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"prompt_number": 19
|
"prompt_number": 9
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Generators"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"A generator is a simple way to construct a new iterable object. Generators return a sequence lazily. When you call the generator, no code is immediately executed until you request elements from the generator.\n",
|
||||||
|
"\n",
|
||||||
|
"Find all the unique ways to make change for $1:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"collapsed": false,
|
||||||
|
"input": [
|
||||||
|
"def squares(n=5):\n",
|
||||||
|
" for i in xrange(1, n + 1):\n",
|
||||||
|
" yield i ** 2\n",
|
||||||
|
"\n",
|
||||||
|
"# No code is executed\n",
|
||||||
|
"gen = squares()\n",
|
||||||
|
"\n",
|
||||||
|
"# Generator returns values lazily\n",
|
||||||
|
"for x in squares():\n",
|
||||||
|
" print x"
|
||||||
|
],
|
||||||
|
"language": "python",
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"output_type": "stream",
|
||||||
|
"stream": "stdout",
|
||||||
|
"text": [
|
||||||
|
"1\n",
|
||||||
|
"4\n",
|
||||||
|
"9\n",
|
||||||
|
"16\n",
|
||||||
|
"25\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"prompt_number": 10
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {}
|
"metadata": {}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user