From 97c7118117465be4606fd145ad8e44006981d8c6 Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Tue, 27 Jan 2015 12:57:08 -0500 Subject: [PATCH] Added snippet for generators. --- core/functions.ipynb | 58 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 5 deletions(-) diff --git a/core/functions.ipynb b/core/functions.ipynb index d68e326..5ddb261 100644 --- a/core/functions.ipynb +++ b/core/functions.ipynb @@ -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": {}