{ "metadata": { "name": "", "signature": "sha256:1afdeae67521bda2e8cf5103d7cc4d80130bc00587a4125e79db6b67e7083ced" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "

\n", "NASA Goddard Space Flight Center
\n", " Python User Group
\n", "2014 Python Boot Camp\n", "

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Advanced Interactions\n", "\n", "Today you're no longer python novices. Now let's try some advanced stuff.\n", "\n", " \u2022\tlambda functions\n", "\t\u2022\tfilter, map, reduce, zip\n", "\t\u2022\ttry, except, finally\n", "\t\u2022\texec, eval\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lambda Functions\n", "\n", "(anonymous functions)\n", "from Lisp & functional programming.\n", "\n", "Allow functions to be defined without an (explicit) identifier." ] }, { "cell_type": "code", "collapsed": false, "input": [ "tmp = lambda x: x**2\n", "print type(tmp)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "tmp(2)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 9, "text": [ "4" ] } ], "prompt_number": 9 }, { "cell_type": "code", "collapsed": false, "input": [ "# forget about creating a new function name...just do it!\n", "(lambda x,y: x**2+y)(2,4.5)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 10, "text": [ "8.5" ] } ], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "## create a list of lambda functions\n", "lamfun = [lambda x: x**2, lambda x: x**3, \\\n", " lambda y: math.sqrt(y) if y >= 0 else \"Really? I mean really? %f\" % y]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "for l in lamfun: print l(-1.3)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1.69\n", "-2.197\n", "Really? I mean really? -1.300000\n" ] } ], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "lambda functions are meant to be short, one liners. If you need more complex functions, probably better just to name them" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### An example: sorting lists\n", "Recall our list of meetings from Monday's Breakout 2 (Advanced Data Structures). Let's understand that one-line solution." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# includes the meeting, room, day, start time(decimal hours), end time\n", "meetings = [(\"Gamma-Ray Burst Lunch\",\"B34 E256\",\"Tue\",12.0,13.0),\\\n", " (\"Extragalactic Journal Club\",\"B34 S391\",\"Tue\",14.0,15.0), \\\n", " (\"Python Users Group\",\"B34 W120A/B\",\"Tue\",14.5,15.5), \\\n", " (\"Astrophysics Colloquium\",\"B34 E215\",\"Tue\",15.5,17.0), \\\n", " (\"NGAPS Happy Hour\",\"B34 E215\",\"Tue\",17.0,18.0), \\\n", " (\"Exoplanet Club\",\"B34 E215\",\"Tue\",11.5,12.5), \\\n", " (\"IS&T Colloquium Series\",\"B3 Auditorium\",\"Tue\",11.0,12.0) ]\n", "\n", "# we'll also define a helpful function to print our sorted schedules\n", "def print_schedule (meetings):\n", " print \"%.32s %.14s %.4s %.5s\" % (\"Meeting\"+32*' ', \"Room No.\"+14*' ', \"Day\"+4*' ', \"Time\"+5*' ')\n", " print \"-\"*60\n", " for meeting in meetings:\n", " print \"%.32s %.14s %.4s %.5s\" % (meeting[0]+32*' ', meeting[1]+14*' ', meeting[2]+4*' ', str(meeting[3])+5*' ')\n" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 13 }, { "cell_type": "code", "collapsed": false, "input": [ "#sort meetings by start time:\n", "meetings.sort(key = lambda x: x[3])\n", "print_schedule(meetings)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Meeting Room No. Day Time \n", "------------------------------------------------------------\n", "IS&T Colloquium Series B3 Auditorium Tue 11.0 \n", "Exoplanet Club B34 E215 Tue 11.5 \n", "Gamma-Ray Burst Lunch B34 E256 Tue 12.0 \n", "Extragalactic Journal Club B34 S391 Tue 14.0 \n", "Python Users Group B34 W120A/B Tue 14.5 \n", "Astrophysics Colloquium B34 E215 Tue 15.5 \n", "NGAPS Happy Hour B34 E215 Tue 17.0 \n" ] } ], "prompt_number": 14 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since the breakout, I've thought of some other meetings I should add to my schedule... but now we need to also sort by the Day of the week, then time." ] }, { "cell_type": "code", "collapsed": false, "input": [ "my_schedule=meetings+[(\"Fermi Journal Club\",\"B34 E256\",\"Wed\",15.5,16.5),\\\n", " (\"SEAL Talk\",\"B34 E215\",\"Thu\",12.0,13.5), \\\n", " (\"SED Director's Seminar\",\"B33 H114\",\"Fri\",12.0,13.0), \\\n", " (\"Engineering Colloquium\",\"B3 Auditorium\",\"Mon\",15.5,16.5), \\\n", " (\"Goddard Scientific Colloquium\",\"B3 Auditorium\",\"Fri\",15.5,16.5), \\\n", " (\"IS&T Colloquium Series\",\"B3 Auditorium\",\"Tue\",11.0,12.0)]\n", "print_schedule(my_schedule)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Meeting Room No. Day Time \n", "------------------------------------------------------------\n", "IS&T Colloquium Series B3 Auditorium Tue 11.0 \n", "Exoplanet Club B34 E215 Tue 11.5 \n", "Gamma-Ray Burst Lunch B34 E256 Tue 12.0 \n", "Extragalactic Journal Club B34 S391 Tue 14.0 \n", "Python Users Group B34 W120A/B Tue 14.5 \n", "Astrophysics Colloquium B34 E215 Tue 15.5 \n", "NGAPS Happy Hour B34 E215 Tue 17.0 \n", "Fermi Journal Club B34 E256 Wed 15.5 \n", "SEAL Talk B34 E215 Thu 12.0 \n", "SED Director's Seminar B33 H114 Fri 12.0 \n", "Engineering Colloquium B3 Auditorium Mon 15.5 \n", "Goddard Scientific Colloquium B3 Auditorium Fri 15.5 \n", "IS&T Colloquium Series B3 Auditorium Tue 11.0 \n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "An easy way to sort lists using multiple columns is \n", "***operator.itemgetter***" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import operator\n", "help(operator.itemgetter)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on class itemgetter in module operator:\n", "\n", "class itemgetter(__builtin__.object)\n", " | itemgetter(item, ...) --> itemgetter object\n", " | \n", " | Return a callable object that fetches the given item(s) from its operand.\n", " | After, f=itemgetter(2), the call f(r) returns r[2].\n", " | After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])\n", " | \n", " | Methods defined here:\n", " | \n", " | __call__(...)\n", " | x.__call__(...) <==> x(...)\n", " | \n", " | __getattribute__(...)\n", " | x.__getattribute__('name') <==> x.name\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes defined here:\n", " | \n", " | __new__ = \n", " | T.__new__(S, ...) -> a new object with type S, a subtype of T\n", "\n" ] } ], "prompt_number": 24 }, { "cell_type": "code", "collapsed": false, "input": [ "# Sort first by day, then by time\n", "my_schedule.sort(key=operator.itemgetter(2,3))\n", "print_schedule(my_schedule)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Meeting Room No. Day Time \n", "------------------------------------------------------------\n", "SED Director's Seminar B33 H114 Fri 12.0 \n", "Goddard Scientific Colloquium B3 Auditorium Fri 15.5 \n", "Engineering Colloquium B3 Auditorium Mon 15.5 \n", "SEAL Talk B34 E215 Thu 12.0 \n", "IS&T Colloquium Series B3 Auditorium Tue 11.0 \n", "IS&T Colloquium Series B3 Auditorium Tue 11.0 \n", "Exoplanet Club B34 E215 Tue 11.5 \n", "Gamma-Ray Burst Lunch B34 E256 Tue 12.0 \n", "Extragalactic Journal Club B34 S391 Tue 14.0 \n", "Python Users Group B34 W120A/B Tue 14.5 \n", "Astrophysics Colloquium B34 E215 Tue 15.5 \n", "NGAPS Happy Hour B34 E215 Tue 17.0 \n", "Fermi Journal Club B34 E256 Wed 15.5 \n" ] } ], "prompt_number": 25 }, { "cell_type": "markdown", "metadata": {}, "source": [ "
*Wait!* That's not what we wanted. Days of the week aren't ordered alphabetically, but we can make that order explicit using a tuple and sort using another lambda function." ] }, { "cell_type": "code", "collapsed": false, "input": [ "days_of_week=('Mon','Tue','Wed','Thu','Fri')\n", "my_schedule.sort(key = lambda x: (days_of_week.index(x[2]),x[3]) )\n", "print_schedule(my_schedule)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Meeting Room No. Day Time \n", "------------------------------------------------------------\n", "Engineering Colloquium B3 Auditorium Mon 15.5 \n", "IS&T Colloquium Series B3 Auditorium Tue 11.0 \n", "IS&T Colloquium Series B3 Auditorium Tue 11.0 \n", "Exoplanet Club B34 E215 Tue 11.5 \n", "Gamma-Ray Burst Lunch B34 E256 Tue 12.0 \n", "Extragalactic Journal Club B34 S391 Tue 14.0 \n", "Python Users Group B34 W120A/B Tue 14.5 \n", "Astrophysics Colloquium B34 E215 Tue 15.5 \n", "NGAPS Happy Hour B34 E215 Tue 17.0 \n", "Fermi Journal Club B34 E256 Wed 15.5 \n", "SEAL Talk B34 E215 Thu 12.0 \n", "SED Director's Seminar B33 H114 Fri 12.0 \n", "Goddard Scientific Colloquium B3 Auditorium Fri 15.5 \n" ] } ], "prompt_number": 28 }, { "cell_type": "markdown", "metadata": {}, "source": [ "##filter, map, reduce, zip\n", "\n", "**filter** is a certain way to do list comprehension\n", "\n", "`filter(function, sequence)` returns a sequence consisting of those items from the sequence for which function(item) is true.\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#Create a list for which numbers between 0 and 100 are even and divisible by 11\n", "\n", "#old way: list comprehension\n", "mylist=[num for num in xrange(101) if (num % 2 == 0.0) and (num % 11 == 0.0)]\n", "print mylist" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[0, 22, 44, 66, 88]\n" ] } ], "prompt_number": 29 }, { "cell_type": "code", "collapsed": false, "input": [ "#new way: filter\n", "def f(num): return (num % 2 == 0.0) and (num % 11 == 0.0)\n", "mylist = filter(f,xrange(101))\n", "print mylist" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[0, 22, 44, 66, 88]\n" ] } ], "prompt_number": 30 }, { "cell_type": "markdown", "metadata": {}, "source": [ "if the input is a string, so is the output..." ] }, { "cell_type": "code", "collapsed": false, "input": [ "## also works on strings...try it with lambdas!\n", "a=\"Charlie Brown said \\\"!@!@$@!\\\"\"; print a" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Charlie Brown said \"!@!@$@!\"\n" ] } ], "prompt_number": 34 }, { "cell_type": "code", "collapsed": false, "input": [ "# Get just the alphabetical characters:\n", "import string\n", "filter(lambda c: c in string.ascii_letters,a)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 35, "text": [ "'CharlieBrownsaid'" ] } ], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**aside: xrange() is an iterable version of range()**\n", "\n", "range(10) creates a 10-element list, xrange(10) creates an iterable object which returns 0 the first time it\u2019s called, 1 then next time, etc. \n", "\n", "\n", "xrange() is an iterable version of range():\n", "range(10) creates a 10-element list,\n", "xrange(10) creates an iterable object which returns 0 the first time it\u2019s called, 1 the next time, etc. \n", "\n", "Why bother? Is there a computational advantage?\n", "\n", "***Time how long it takes with the ipython magic %timeit:***" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def f(num): return (num % 2 == 0.0) and (num % 11 == 0.0)\n", "%timeit len(filter(f,range(1L)))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "100000 loops, best of 3: 1.93 \u00b5s per loop\n" ] } ], "prompt_number": 30 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit len(filter(f,xrange(1L))) " ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1000000 loops, best of 3: 1.27 \u00b5s per loop\n" ] } ], "prompt_number": 31 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `map()` is just another way to do list comprehension ###\n", "\n", "`map(function, sequence)` calls `function(item)` for each of the sequence's items and returns a list of the return values" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def cube_it(x): return x**3\n", "\n", "map(cube_it,xrange(1,10))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 32, "text": [ "[1, 8, 27, 64, 125, 216, 343, 512, 729]" ] } ], "prompt_number": 32 }, { "cell_type": "code", "collapsed": false, "input": [ "map(lambda x: x**3, xrange(1,10))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 33, "text": [ "[1, 8, 27, 64, 125, 216, 343, 512, 729]" ] } ], "prompt_number": 33 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `reduce()` returns one value ###\n", "\n", "reduce(function, sequence) returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# sum from 1 to 10\n", "reduce(lambda x,y: x + y, xrange(1,11))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 36, "text": [ "55" ] } ], "prompt_number": 36 }, { "cell_type": "code", "collapsed": false, "input": [ "%timeit reduce(lambda x,y: x + y, xrange(1,11))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "100000 loops, best of 3: 2.01 \u00b5s per loop\n" ] } ], "prompt_number": 40 }, { "cell_type": "code", "collapsed": false, "input": [ "# sum() is a built in function... so it\u2019s bound to be faster\n", "%timeit sum(xrange(1,11))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1000000 loops, best of 3: 629 ns per loop\n" ] } ], "prompt_number": 41 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `zip()` ###\n", "\n", "built in function to pairwise concatenate items in iterables into a list of tuples" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print zip([\"I\",\"you\",\"them\"],[\"=spam\",\"=eggs\",\"=dark knights\"])\n", "print zip([\"I\",\"you\",\"them\"],[\"=spam\",\"=eggs\",\"=dark knights\"],[\"!\",\"?\",\"#\"])\n", "print zip([\"I\",\"you\",\"them\"],[\"=spam\",\"=eggs\",\"=dark knights\"],[\"!\",\"?\"])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[('I', '=spam'), ('you', '=eggs'), ('them', '=dark knights')]\n", "[('I', '=spam', '!'), ('you', '=eggs', '?'), ('them', '=dark knights', '#')]\n", "[('I', '=spam', '!'), ('you', '=eggs', '?')]\n" ] } ], "prompt_number": 42 }, { "cell_type": "code", "collapsed": false, "input": [ "questions = ['name', 'quest', 'favorite color']\n", "answers = ['lancelot', 'the holy grail', 'blue']\n", "for q, a in zip(questions, answers):\n", " print 'What is your %s? It is %s.' % (q, a)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "What is your name? It is lancelot.\n", "What is your quest? It is the holy grail.\n", "What is your favorite color? It is blue.\n" ] } ], "prompt_number": 44 }, { "cell_type": "markdown", "metadata": {}, "source": [ "not to be confused with `zipfile` module which exposes file compression " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `try`, `except`, `finally`\n", "\n", "Not all of our code is well-written. Here's how we can manage." ] }, { "cell_type": "code", "collapsed": true, "input": [ "# what happens when you don't give a number?\n", "tmp = raw_input(\"Enter a number and I'll square it: \")\n", "print float(tmp)**2" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter a number and I'll square it: no\n" ] }, { "ename": "ValueError", "evalue": "could not convert string to float: no", "output_type": "pyerr", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# what happens when you don't give a number?\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mtmp\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mraw_input\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Enter a number and I'll square it: \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtmp\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: could not convert string to float: no" ] } ], "prompt_number": 45 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Solution: Wrap volatile code in try/except/finally\n", "![diagram of try, except, finally](https://raw.githubusercontent.com/kialio/python-bootcamp/master/DataFiles_and_Notebooks/07_AdvancedInteractions/tryexceptfinally.png)\n" ] }, { "cell_type": "code", "collapsed": true, "input": [ "#this code can gracefully handle non-numbers\n", "try: \n", " tmp = raw_input(\"Enter a number \u201c + and I'll square it: \")\n", " print float(tmp)**2\n", "except:\n", " print \"dude. I asked you for a number and \" + \"%s is not a number.\" % tmp\n", "finally:\n", " print \"thanks for playing!\"" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter a number \u201c + and I'll square it: \n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "dude. I asked you for a number and is not a number.\n", "thanks for playing!\n" ] } ], "prompt_number": 48 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### A quick work on exception handling in python\n", "\n", " * errors in Python generate what are called \u201cexceptions\u201d\n", " * exceptions can be handled differently depending on what kind of exception they are. (we\u2019ll see more of that later)\n", " * except \u201ccatches\u201d these exceptions\n", " * you do not have to catch exceptions (try/finally) is allowed. Finally block is executed no matter what! " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `exec`, `eval`\n", "\n", "`exec` executes strings as if they were Python code." ] }, { "cell_type": "code", "collapsed": true, "input": [ "a = \"print 'checkit' \"\n", "exec a" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "checkit\n" ] } ], "prompt_number": 49 }, { "cell_type": "code", "collapsed": true, "input": [ "a = \"x = 4.56\"\n", "exec a\n", "print x" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "4.56\n" ] } ], "prompt_number": 50 }, { "cell_type": "code", "collapsed": true, "input": [ "exec \"del x\"\n", "print x" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'x' is not defined", "output_type": "pyerr", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mexec\u001b[0m \u001b[0;34m\"del x\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'x' is not defined" ] } ], "prompt_number": 51 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This has some clear benefits:\n", " * dynamically create Python code\n", " * execute that code w/ implication for current namespace " ] }, { "cell_type": "code", "collapsed": false, "input": [ "# try the following answers:\n", "#what built in function would you like me to coopt? math.sin\n", "#what new name would you like to give it? monty_sin\n", "#what built in function would you like me to coopt? Range\n", "#what new name would you like to give it? python_range\n", "\n", "import math\n", "while True:\n", " bi = raw_input(\"what built in function would you like me to coopt? \")\n", " nn = raw_input(\"what new name would you like to give it? \")\n", " exec \"%s = %s\" % (nn,bi)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": true, "input": [ "# If you tried turning math.sin into monty_sin \n", "# and range into python_range this will work!\n", "print monty_sin (math.pi/2)\n", "print python_range(3)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`eval` evaluates strings as Python expressions " ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = eval('5') ; print x\n", "x = eval('abs(%d)' % -100) ; print x" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "x = eval('print 5')" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "exec \"print 5\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "5\n" ] } ], "prompt_number": 113 }, { "cell_type": "code", "collapsed": false, "input": [ "x = eval('if 1: x = 4')" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 1)", "output_type": "pyerr", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m if 1: x = 4\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "prompt_number": 114 }, { "cell_type": "code", "collapsed": false, "input": [ "exec \"if True: x=4\" ; x" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 115, "text": [ "4" ] } ], "prompt_number": 115 }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "Now you have all the tools you need to write code that practically writes itself..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##Breakout 7\n", "\n", "Survival Driven Development\n", "===========================\n", "\n", "Survival Driven Development (SDD) is the newest software development fad. In this development framework, you specify what the software is supposed to do, then randomly generate source code to fulfill these requirements. Most of these attempts will fail, but hopefully one will succeed.\n", "\n", "Your task is to use SDD to make a function to approximate `x**2 + x`.\n", "\n", "Hint 1: Randomly generate lambda functions using a restricted vocabulary of source fragments.
\n", "`vocab = ['x', 'x', ' ', '+', '-', '*', '/', '1', '2', '3']`\n", "\n", "Hint 2: Only evaluate `x` at a small-ish number of values and save the difference between those answers and the true value of `x**2 + x`.\n", "\n", "Hint 3: SDD is error prone. Be sure to catch your errors!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![How could you possibly think typing \"import skynet\" was a good idea?](http://imgs.xkcd.com/comics/2008_christmas_special.png)" ] }, { "cell_type": "code", "collapsed": true, "input": [ "# if you were having trouble getting started...\n", "import random\n", "import numpy\n", "\n", "vocab = [\"x\",\"x\",\"\",\"+\",\"-\",\"*\",\"/\",\"1\",\"2\",\"3\"]\n", "\n", "max_try = 1000000\n", "max_chars = 10 #max number of characters to generate\n", "x_array = numpy.arange(-3,3,0.4) # over a smallish range\n", "real_function = x_array**2 + x_array\n", "\n", "tries = []\n", "\n", "# for loop...\n", "# you fill in the rest" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 16 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 17, "text": [ "1L" ] } ], "prompt_number": 17 } ], "metadata": {} } ] }