Added snippet for generators.

This commit is contained in:
Donne Martin 2015-01-27 12:57:08 -05:00
parent 900b493e54
commit 97c7118117

View File

@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
"signature": "sha256:1123ef3475d906de39c34c42c18ebeda8c0f1c60ee01b6e692125a51b325d8e7"
"signature": "sha256:a81c81558508aed1c6f336342652e5f8dcc250ecd9f9f955b9e6e02d65a45c5c"
},
"nbformat": 3,
"nbformat_minor": 0,
@ -394,13 +394,13 @@
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 18,
"prompt_number": 8,
"text": [
"10"
]
}
],
"prompt_number": 18
"prompt_number": 8
},
{
"cell_type": "markdown",
@ -423,13 +423,61 @@
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 19,
"prompt_number": 9,
"text": [
"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": {}