{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Advanced Interactions\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lambda Functions ###\n", "\n", "(anonymous functions)\n", "from Lisp & functional programming" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tmp = lambda x: x**2\n", "print(type(tmp))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tmp(2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# forget about creating a new function name...just do it!\n", "(lambda x,y: x**2+y)(2,4.5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "## 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]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "for l in lamfun: print(l(-1.3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "lambda functions are meant to be short, one liners. If you need more complex functions, probably better just to name them\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# %load airline.py\n", "airports = {\"DCA\": \"Washington, D.C.\", \"IAD\": \"Dulles\", \"LHR\": \"London-Heathrow\", \\\n", " \"SVO\": \"Moscow\", \"CDA\": \"Chicago-Midway\", \"SBA\": \"Santa Barbara\", \"LAX\": \"Los Angeles\",\\\n", " \"JFK\": \"New York City\", \"MIA\": \"Miami\", \"AUM\": \"Austin, Minnesota\"}\n", " \n", "# airline, number, heading to, gate, time (decimal hours) \n", "flights = [(\"Southwest\",145,\"DCA\",1,6.00),(\"United\",31,\"IAD\",1,7.1),(\"United\",302,\"LHR\",5,6.5),\\\n", " (\"Aeroflot\",34,\"SVO\",5,9.00),(\"Southwest\",146,\"CDA\",1,9.60), (\"United\",46,\"LAX\",5,6.5),\\\n", " (\"Southwest\",23,\"SBA\",6,12.5),(\"United\",2,\"LAX\",10,12.5),(\"Southwest\",59,\"LAX\",11,14.5),\\\n", " (\"American\", 1,\"JFK\",12,11.3),(\"USAirways\", 8,\"MIA\",20,13.1),(\"United\",2032,\"MIA\",21,15.1),\\\n", " (\"SpamAir\",1,\"AUM\",42,14.4)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "help(list.sort)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "flights.sort(key=lambda x: x[4]) ; \n", "print(flights)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import pprint\n", "pprint.pprint(flights)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiple column sorting\n", "\n", "```python\n", "operator.itemgetter(item[, args...])¶\n", "```\n", "\n", "Return a callable object that fetches item from its operand using the operand’s `__getitem__()` method. If multiple items are specified, returns a tuple of lookup values. \n", "\n", "http://docs.python.org/library/operator.html#module-operator" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import operator\n", "flights.sort(key=operator.itemgetter(4,1,0))\n", "flights" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 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" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mylist=[num for num in range(101) if (num & 2) and (num & 1) and (num % 11 != 0.0)]\n", "print(mylist)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def f(num): return (num & 2) and (num & 1) and (num % 11 != 0.0)\n", "\n", "mylist = list(filter(f,range(101)))\n", "print(mylist)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mylist = list(map(lambda num: (num & 2) and (num & 1) and (num % 11 != 0.0),range(101)))\n", "print(mylist)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "if the input is a string, so is the output..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "## also works on strings...try it with lambdas!\n", "import string\n", "a=\"Charlie Brown said \\\"!@!@$@!\\\"\"\n", "\"\".join([c for c in a if c in string.ascii_letters])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "\", \".join([str(num) for num in range(101) if (num & 2) and \\\n", " (num & 1) and (num % 11 != 0.0)])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[back]\n", "### Map is just another way to do list comprehension ###" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def timesthree(x): return x*3\n", "list(map(timesthree,\"spam\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "list(map(lambda x: x**3, range(1,10)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reduce returns one value ###\n", "\n", "reduce(function, sequence) returns a single value constructed by calling the binary function on the first two items of the sequence, then on the result and the next item, and so on" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from functools import reduce\n", "# sum from 1 to 10\n", "reduce(lambda x,y: x + y, range(1,11)) \n", "%timeit reduce(lambda x,y: x + y, range(1,11))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "reduce(lambda x,y: x + y, range(11,1,-1)) " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "list(range(11,1,-1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = [\"a\",\"b\"]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "reduce?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# sum() is a built in function...it’s bound to be faster\n", "%timeit sum(range(1,11))" ] }, { "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", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "list(zip([\"I\",\"you\",\"them\"],[\"=spam\",\"=eggs\",\"=dark knights\"]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "list(zip([\"I\",\"you\",\"them\"],[\"=spam\",\"=eggs\",\"=dark knights\"],[\"!\",\"?\",\"#\"]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = list(zip([\"I\",\"you\",\"them\"],[\"=spam\",\"=eggs\",\"=dark knights\"],[\"!\",\"?\",\"hello\",\"blah\"]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a[0][1] = \"=eggs\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "questions = ['name', 'quest', 'favorite color']\n", "answers = ['lancelot', 'the holy grail', 'blue']\n", "for a,q in zip(questions, answers):\n", " print('What is your %s? It is %s' % (q,a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "not to be confused with `zipfile` module which exposes file compression " ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# try, except, finally\n", "\n", " - Billy: Let's keep going with \"Airplanes\", for \\$200.\n", " - Bobby Wheat: \"Airplanes\" for \\$200: \"And what is the Deal With the Black Box?\" \n", " - [ Tommy buzzes in ] Tommy!\n", " - Tommy: It's the only thing that survives the crash - why don't they build the whole plane out of the Black Box!\n", "\n", "http://snltranscripts.jt.org/91/91rstandup.phtml\n", "\n", "http://www.nbc.com/saturday-night-live/video/standup-and-win/2868123\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Wrap volatile code in try/except/finally\n", "\n", "instead of ..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tmp = input(\"Enter a number and I'll square it: \") ; print(float(tmp)**2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "do this..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def f():\n", " try:\n", " tmp = input(\"Enter a number 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!\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "f()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Wrap volatile code in try/except/finally\n", "\n", "```python\n", "try:\n", " # volatile stuff here\n", " tmp = raw_input(\"Enter a number “ + \\\n", " and I'll square it: \")\n", " print(float(tmp)**2)\n", "except:\n", " # upon error, jump here inside except and execute that code\n", " print(\"dude. I asked you for a number and \" + \\\n", " \"%s is not a number.\" % tmp)\n", "finally:\n", " # regardless of whether you hit an error, execute everything inside the finally block\n", " print(\"thanks for playing!\")\n", "```\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "try:\n", " print(\"eat at\" % joes)\n", "finally:\n", " print(\"bye.\") " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " - errors in Python generate what are called “exceptions”\n", " - exceptions can be handled differently depending on what kind of exception they are (we’ll see more of that later)\n", " - except “catches” 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` is a statement which executes strings as if they were Python code " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = \"print('checkit')\"\n", "print(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "exec(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = \"x = 4.56\" " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "exec(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "exec(\"del x\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- dynamically create Python code (!)\n", "- execute that code w/ implications for current namespace" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import math\n", "while True:\n", " bi = input(\"what built in function would you like me to coopt? \")\n", " if bi in ('?',\"\",'end'):\n", " break\n", " nn = input(\"what new name would you like to give it? \")\n", " exec(\"%s = %s\" % (nn,bi))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "jsin(math.pi/2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`eval` is an expression which evaluates strings as Python expressions " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = eval('5') ; print(x) # x <- 5\n", "x = eval('%d + 6' % x) ; print(x) # x <- 11\n", "x = eval('abs(%d)' % -100) ; print(x) # x <- 100" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "eval('if 1: x = 4') # INVALID; if is a statement, not an expression." ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "# Breakout\n", "\n", "Write a code which generates python code that approximates the function:\n", "$$x^2 + x$$\n", "\n", "hints:\n", "\n", "- randomly generate `lambda` functions using a restricted vocabulary: \n", " `voc =[\"x\",\"x\",\" \",\"+\",\"-\",\"*\",\"/\",\"1\",\"2\",\"3\"]`\n", "\n", "- evaluate these `lambda` functions at a fix number of x values and save the difference between those answers and `x**2 + x`\n", "\n", "- catch errors!\n", "\n", "- start with a file like:\n", "\n", "```python\n", "import random\n", "import numpy\n", "\n", "voc =[\"x\",\"x\",\" \",\"+\",\"-\",\"*\",\"/\",\"1\",\"2\",\"3\"]\n", "\n", "nfunc = 1000000\n", "maxchars = 10 # max how many characters to gen\n", "eval_places = numpy.arange(-3,3,0.4)\n", "sin_val = eval_places**2 + eval_places\n", "tries = []\n", "for loop...\n", "```\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }