{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Basic Scripting with Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"Regular coding\", as some compiled languages like C and Fortran, is also possible in Python, where everything is made explicitly.\n", "Although regular coding is less abstract and more clear, in most cases it is also less efficient. Fortunately, features of Python like operators overloading, easy import of auxiliar libraries and the OOP (Object-Oriented Programming) paradigm make Python very efficient and saving when coding.\n", "\n", "\n", "The goal of this session is to learn several tools offered by Python and auxiliar libraries for basic tasks like data manipulation, evaluating functions, argument passing, search methods, etc." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- - - \n", "**For the proposed activities:**\n", "\n", "- **Do not hesitate to take your first guess when writing your own codes! (by now)**\n", "- **Do not try other ways more complex or less natural for YOU yet!**\n", "- **It is also important that you work alone, so you can contrast later YOUR way with the alternative offered by Python!**\n", "\n", "- - - " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- [Example 1](#Example-1) \n", "- [Example 2](#Example-2)\n", "- [Miscellanea](#Miscellanea)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- - - " ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Example 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write a program that calculates the sum of N numbers" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/python\n", "#====================================================================\n", "#REGULAR\n", "#====================================================================\n", "N = 5\n", "numbers = [1,5,2,3,2]\n", "suma = 0\n", "for i in xrange(0,N,1):\n", " suma += numbers[i]\n", "print \"The result is %d\"%(suma)\n", "#====================================================================\n", "#PYTHON 1\n", "#====================================================================\n", "numbers = [1,5,2,3,2]\n", "suma = 0\n", "for i in numbers:\n", " suma += i\n", "print \"The result is %d\"%(suma)\n", "#====================================================================\n", "#PYTHON 2\n", "#====================================================================\n", "numbers = [1,5,2,3,2]\n", "print \"The result is %d\"%(sum(numbers))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The result is 13\n", "The result is 13\n", "The result is 13\n" ] } ], "prompt_number": 1 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Example 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write a program that generates a grid for the function:\n", "\n", "$$f(x) = x \\sqrt{1+x^2}$$\n", "\n", "in the range $1\\leq x < 5\\ \\ \\ $ with a step of $0.5$." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/python\n", "#====================================================================\n", "#REGULAR \n", "#====================================================================\n", "dx = 0.5\n", "xmin = 1\n", "xmax = 5\n", "N = int((xmax-xmin)/dx)\n", "#Function\n", "def f(x):\n", " return x*(1+x**2)**0.5\n", "#Array x and y=f(x)\n", "X = []\n", "Y = []\n", "for i in xrange(0,N,1):\n", " X.append(xmin + i*dx)\n", " Y.append(f(X[i]))\n", " print \"Plain: f(%1.1f)=%1.1f\"%( X[i], Y[i] )\n", "#====================================================================\n", "#PYTHON \n", "#====================================================================\n", "import numpy as np\n", "dx = 0.5\n", "xmin = 1\n", "xmax = 5\n", "X = np.arange(xmin,xmax,dx)\n", "f = lambda x: x*(1+x**2)**0.5\n", "Y = f(X)\n", "for x,y in zip(X,Y):\n", " print \"Python: f(%1.1f)=%1.1f\"%( x, y )" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Plain: f(1.0)=1.4\n", "Plain: f(1.5)=2.7\n", "Plain: f(2.0)=4.5\n", "Plain: f(2.5)=6.7\n", "Plain: f(3.0)=9.5\n", "Plain: f(3.5)=12.7\n", "Plain: f(4.0)=16.5\n", "Plain: f(4.5)=20.7\n", "Python: f(1.0)=1.4" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Python: f(1.5)=2.7\n", "Python: f(2.0)=4.5\n", "Python: f(2.5)=6.7\n", "Python: f(3.0)=9.5\n", "Python: f(3.5)=12.7\n", "Python: f(4.0)=16.5\n", "Python: f(4.5)=20.7\n" ] } ], "prompt_number": 3 }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Miscellanea" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Solve the next exercises:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**1.** Write a program that sort a list of N numbers." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/python\n", "import numpy as np\n", "\n", "N = 5\n", "#The set is generated randomly\n", "X = np.random.random(N)\n", "print \"Original set:\", X\n", "print \"Sorted set:\", np.sort(X)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Original set: [ 0.60423365 0.06462303 0.01382518 0.58877186 0.63548625]\n", "Sorted set: [ 0.01382518 0.06462303 0.58877186 0.60423365 0.63548625]\n" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**2.** Find all the elements of a list of N numbers that are greater than the mean value of them. Then, create a new list with those numbers." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/python\n", "import numpy as np\n", "\n", "N = 10\n", "#The set is generated randomly\n", "X = 100*np.random.random(N)\n", "Y = X[ X>=X.mean() ]\n", "print \"Original set\", X\n", "print \"Numbers greater than %1.2f:\"%(X.mean()), Y" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Original set [ 0.88939513 17.434237 58.54453737 3.66019105 5.22876937\n", " 26.54719482 76.98181862 75.8326774 57.25619751 60.1402436 ]\n", "Numbers greater than 38.25: [ 58.54453737 76.98181862 75.8326774 57.25619751 60.1402436 ]\n" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**3.** Write a program that gives the name of students who passed a course (grade$\\geq 3.0\\ \\ $ over $5.0\\ \\ $)." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/python\n", "import numpy as np\n", "\n", "#All students\n", "grades = {\"Juanito\":2.5, \"Pepito\":4.8, \"Carlitos\":3.0, \"Maria\":3.9, \"Pepita\":4.6, \"Anita\":1.9, \"Bertulfo\":0.9}\n", "\n", "#Students that approved\n", "winners = np.array(grades.keys())[ np.array(grades.values())>=3.0 ]\n", "print \"The next students approved:\", winners" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The next students approved: ['Pepito' 'Carlitos' 'Pepita' 'Maria']\n" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**4.** Write a program that evaluates the next expression for given values of $x$, $a$ and $b$:\n", "\n", "$$\\frac{\\sin(x) + \\cos(x)}{2}(a+b)$$\n", "\n", "you may find useful the library `math` for the functions $\\sin(x)\\ \\ $ and $\\cos(x)$. Import it as `import math`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**5.** Find all the prime numbers between 1 and 100." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/python\n", "import numpy, math\n", "\n", "#Prime Checker\n", "def primes(upto):\n", " primes = numpy.arange(3,upto+1,2)\n", " isprime = numpy.ones((upto-1)/2,dtype=bool)\n", " for factor in primes[:int(math.sqrt(upto))]:\n", " if isprime[(factor-2)/2]: isprime[(factor*3-2)/2::factor]=0\n", " return numpy.insert(primes[isprime],0,2)\n", "\n", "print \"The prime numbers between 1 and 100 are:\", primes(100)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The prime numbers between 1 and 100 are: [ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]\n" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**6.** Write a program that calculates the factorial of a given number." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/python\n", "N = 5\n", "#Factorial function\n", "def factorial(N):\n", " if N==1:\n", " return 1\n", " else:\n", " return N*factorial(N-1)\n", " \n", "print \"The factorial of %d is %d\"%(N, factorial(N))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The factorial of 5 is 120\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**7.** Write a program that evaluates the $\\cos(x)\\ \\ $ function by using the Taylor expansion using $2$, $5$ and $10$ terms.\n", "\n", "$$\\cos(x) = \\sum_{n=0}^\\infty \\frac{(-1)^n}{(2n!)}x^{2n}\\ \\ \\ $$ for all $$x$$" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/python\n", "from __future__ import division\n", "import math\n", "\n", "#Number of terms\n", "N = [2,5,10]\n", "x = 1.5\n", "\n", "#Taylor expansion of cos(x)\n", "def taylor_cos( x, N ):\n", " term = lambda x,n: (-1)**n/(math.factorial(2*n))*x**(2*n)\n", " return np.sum( [term(x,n) for n in xrange(0,N)] )\n", "\n", "for n in N:\n", " print \"Taylor expansion of cos(%1.2f) for %d terms: %1.6f\"%( x, n, taylor_cos(x,n) )\n", "print \"Exact value of cos(%1.2f): %1.6f\"%( x, math.cos(x) )" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Taylor expansion of cos(1.50) for 2 terms: -0.125000\n", "Taylor expansion of cos(1.50) for 5 terms: 0.070753\n", "Taylor expansion of cos(1.50) for 10 terms: 0.070737\n", "Exact value of cos(1.50): 0.070737\n" ] } ], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**8.** Write a program that calculates $\\pi$ by using the next approximations:\n", "\n", "$$\\frac{2}{\\pi} = \\frac{\\sqrt{2}}{2}\\times \\frac{\\sqrt{2+\\sqrt{2}}}{2}\\times \\frac{\\sqrt{2+\\sqrt{2+\\sqrt{2}}}}{2}\\times \\cdots $$\n", "\n", "and\n", "\n", "$$\\frac{\\pi}{4} = 1 - \\frac{1}{3} + \\frac{1}{5} - \\frac{1}{7} + \\frac{1}{9} - \\frac{1}{11} + \\cdots$$\n", "\n", "Which approximation takes less terms for achieving a good accuracy?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- - - " ] } ], "metadata": {} } ] }