"Regular coding", as some compiled languages like C and Fortran, is also possible in Python, where everything is made explicitly. 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.
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.
For the proposed activities:
Write a program that calculates the sum of N numbers
#! /usr/bin/python
#====================================================================
#REGULAR
#====================================================================
N = 5
numbers = [1,5,2,3,2]
suma = 0
for i in xrange(0,N,1):
suma += numbers[i]
print "The result is %d"%(suma)
#====================================================================
#PYTHON 1
#====================================================================
numbers = [1,5,2,3,2]
suma = 0
for i in numbers:
suma += i
print "The result is %d"%(suma)
#====================================================================
#PYTHON 2
#====================================================================
numbers = [1,5,2,3,2]
print "The result is %d"%(sum(numbers))
The result is 13 The result is 13 The result is 13
Write a program that generates a grid for the function:
$$f(x) = x \sqrt{1+x^2}$$in the range $1\leq x < 5\ \ \ $ with a step of $0.5$.
#! /usr/bin/python
#====================================================================
#REGULAR
#====================================================================
dx = 0.5
xmin = 1
xmax = 5
N = int((xmax-xmin)/dx)
#Function
def f(x):
return x*(1+x**2)**0.5
#Array x and y=f(x)
X = []
Y = []
for i in xrange(0,N,1):
X.append(xmin + i*dx)
Y.append(f(X[i]))
print "Plain: f(%1.1f)=%1.1f"%( X[i], Y[i] )
#====================================================================
#PYTHON
#====================================================================
import numpy as np
dx = 0.5
xmin = 1
xmax = 5
X = np.arange(xmin,xmax,dx)
f = lambda x: x*(1+x**2)**0.5
Y = f(X)
for x,y in zip(X,Y):
print "Python: f(%1.1f)=%1.1f"%( x, y )
Plain: f(1.0)=1.4 Plain: f(1.5)=2.7 Plain: f(2.0)=4.5 Plain: f(2.5)=6.7 Plain: f(3.0)=9.5 Plain: f(3.5)=12.7 Plain: f(4.0)=16.5 Plain: f(4.5)=20.7 Python: f(1.0)=1.4 Python: f(1.5)=2.7 Python: f(2.0)=4.5 Python: f(2.5)=6.7 Python: f(3.0)=9.5 Python: f(3.5)=12.7 Python: f(4.0)=16.5 Python: f(4.5)=20.7
Solve the next exercises:
1. Write a program that sort a list of N numbers.
#! /usr/bin/python
import numpy as np
N = 5
#The set is generated randomly
X = np.random.random(N)
print "Original set:", X
print "Sorted set:", np.sort(X)
Original set: [ 0.60423365 0.06462303 0.01382518 0.58877186 0.63548625] Sorted set: [ 0.01382518 0.06462303 0.58877186 0.60423365 0.63548625]
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.
#! /usr/bin/python
import numpy as np
N = 10
#The set is generated randomly
X = 100*np.random.random(N)
Y = X[ X>=X.mean() ]
print "Original set", X
print "Numbers greater than %1.2f:"%(X.mean()), Y
Original set [ 0.88939513 17.434237 58.54453737 3.66019105 5.22876937 26.54719482 76.98181862 75.8326774 57.25619751 60.1402436 ] Numbers greater than 38.25: [ 58.54453737 76.98181862 75.8326774 57.25619751 60.1402436 ]
3. Write a program that gives the name of students who passed a course (grade$\geq 3.0\ \ $ over $5.0\ \ $).
#! /usr/bin/python
import numpy as np
#All students
grades = {"Juanito":2.5, "Pepito":4.8, "Carlitos":3.0, "Maria":3.9, "Pepita":4.6, "Anita":1.9, "Bertulfo":0.9}
#Students that approved
winners = np.array(grades.keys())[ np.array(grades.values())>=3.0 ]
print "The next students approved:", winners
The next students approved: ['Pepito' 'Carlitos' 'Pepita' 'Maria']
4. Write a program that evaluates the next expression for given values of $x$, $a$ and $b$:
$$\frac{\sin(x) + \cos(x)}{2}(a+b)$$you may find useful the library math
for the functions $\sin(x)\ \ $ and $\cos(x)$. Import it as import math
5. Find all the prime numbers between 1 and 100.
#! /usr/bin/python
import numpy, math
#Prime Checker
def primes(upto):
primes = numpy.arange(3,upto+1,2)
isprime = numpy.ones((upto-1)/2,dtype=bool)
for factor in primes[:int(math.sqrt(upto))]:
if isprime[(factor-2)/2]: isprime[(factor*3-2)/2::factor]=0
return numpy.insert(primes[isprime],0,2)
print "The prime numbers between 1 and 100 are:", primes(100)
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]
6. Write a program that calculates the factorial of a given number.
#! /usr/bin/python
N = 5
#Factorial function
def factorial(N):
if N==1:
return 1
else:
return N*factorial(N-1)
print "The factorial of %d is %d"%(N, factorial(N))
The factorial of 5 is 120
7. Write a program that evaluates the $\cos(x)\ \ $ function by using the Taylor expansion using $2$, $5$ and $10$ terms.
$$\cos(x) = \sum_{n=0}^\infty \frac{(-1)^n}{(2n!)}x^{2n}\ \ \ $$for all $$x$$
#! /usr/bin/python
from __future__ import division
import math
#Number of terms
N = [2,5,10]
x = 1.5
#Taylor expansion of cos(x)
def taylor_cos( x, N ):
term = lambda x,n: (-1)**n/(math.factorial(2*n))*x**(2*n)
return np.sum( [term(x,n) for n in xrange(0,N)] )
for n in N:
print "Taylor expansion of cos(%1.2f) for %d terms: %1.6f"%( x, n, taylor_cos(x,n) )
print "Exact value of cos(%1.2f): %1.6f"%( x, math.cos(x) )
Taylor expansion of cos(1.50) for 2 terms: -0.125000 Taylor expansion of cos(1.50) for 5 terms: 0.070753 Taylor expansion of cos(1.50) for 10 terms: 0.070737 Exact value of cos(1.50): 0.070737
8. Write a program that calculates $\pi$ by using the next approximations:
$$\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 $$and
$$\frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \frac{1}{11} + \cdots$$Which approximation takes less terms for achieving a good accuracy?