x=input('Enter an integer (x): ')y=input('Enter another one (y): ')print('The sum is = ',x+y)# print as numeric, input
123
Enter an integer (x): 1
Enter another one (y): 2
('The sum is = ', 3)
t=raw_input('Enter an integer: ')u=raw_input('Enter another one: ')print('The sum is = ',t+u)# print as string, raw input
123
Enter an integer: 2
Enter another one: 3
('The sum is = ', '23')
v=input('Enter an integer: ')w=input('Enter another one: ')print('The sum is = ',str(v)+str(w))# print as string, input changes into a string
123
Enter an integer: 1
Enter another one: 1
('The sum is = ', '11')
y1=raw_input('Enter an integer: ')y2=raw_input('Enter another one: ')print('The sum is = ',int(y1)+int(y2))# print as numeric, raw input changed into integer
123
Enter an integer: 2
Enter another one: 2
('The sum is = ', 4)
y3=raw_input('Enter an integer: ')y4=raw_input('Enter another one: ')print('The sum is = ',float(y3)+float(y4))# print as numeric, raw input changed into float
123
Enter an integer: 1
Enter another one: 2
('The sum is = ', 3.0)
# simplify the code, shorten the lineyear=input('year: ')month=input('month: ')if1900<year<2100\
and1<=month<=12:print('I am so long and will\ not fit in a single line')
# create the filef=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes1.txt','w')f.write('This is a test file')# write inf.close()
# read itf=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes1.txt','r')print(f.read())f.close()
1
This is a test file
# read it againf=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes1.txt','r')print(f.read(7))# get first seven characters on the consoleprint(f.read())# get the remaining onesf.close()
12
This is
a test file
# create itf=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes2.txt','w')forkinrange(1,10):# 1, 2, 3 stop before 4s='%3d\n'%(k)# no format 3d, new linef.write(s)# write inf.close()
# read itf=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes2.txt','r')# openprint(f.read())f.close()
123456789
1
2
3
4
5
6
7
8
9
# read it horizontallyf=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes2.txt','r')# openprint(f.read(),)f.close()
1
(' 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n',)
f=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes2.txt','r')while1:# infinite loops=f.readline()ifs=='':# Empty string means end of filebreak# terminate the loopm=int(s)# Convert to integerprint(m*5),f.close()
1
51015202530354045
# create itf=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes3.txt','w')f.write('')f.close()
# give an error if there is a blank line in the file# test it (without the if, there would be an error)f=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes3.txt','r')while1:# infinite loops=f.readline()ifs=='':# empty string means end of filebreak# terminate the loopm=int(s)# convert to integerprint(m*5)f.close()
# alternativelyf=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes3.txt','r')while1:# infinite loops=f.readline()iflen(s)<1:# string with no valuebreak# terminate the loopm=int(s)# convert to integerprint(m*5)f.close()
Strings can easily be written to and read from a le. Numbers take a bit more eort, since the read() method only returns Strings, which will have to be converted in to a number explicitly. However, when you want to save and restore data types like lists, dictionaries, or class instances, things get a lot more complicated. Rather than have the users constantly writing and debugging code to save complicated data types, Python provides a standard module called pickle.
The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1] or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
importpicklef=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes4.txt','w')pickle.dump(12.3,f)# write a float typef.close()
f=open('D:/Admin_Hugues/Documents/Notebooks/Python for Education/notes4.txt','r')x=pickle.load(f)print(x,type(x))# check the type of data readf.close()
The GUI programs are event-driven like a macro. Create Widgets like a Button, Label, Canvas, etc. The first step is to create a main graphics window by calling the function Tk().
# Example tkmain.py# open an empty box with min, max, close buttonsimportTkinterastkroot=tk.Tk()root.mainloop()# it opens a windows!
# Example tklabel.pyroot=tk.Tk()w=tk.Label(root,text="Hello, world")w.pack()root.mainloop()# it opens a windows with the text in it
# Example tkbutton.pydefhello():print('hello world')w=tk.Tk()# Creates the main Graphics windowb=tk.Button(w,text='Click Me',command=hello)b.pack()w.mainloop()# it opens a windows with a button; after clicking, it print the function
1
hello world
# Example tkcanvas.pydefdraw(event):c.create_rectangle(event.x, \
event.y,event.x+5,event.y+5)w=tk.Tk()c=tk.Canvas(w,width=300,height=200)c.pack()c.bind("<Button-1>",draw)w.mainloop()# it open a windows; you can left-click and add dots in it
# Example tkcanvas2.pyrecs=[]# list keeping track of the rectanglesdefremove(event):globalrecsiflen(recs)>0:c.delete(recs[0])# delete from Canvasrecs.pop(0)# delete first item from listdefdraw(event):globalrecsr=c.create_rectangle(event.x, \
event.y,event.x+5,event.y+5)recs.append(r)w=tk.Tk()c=tk.Canvas(w,width=300,height=200)c.pack()c.bind("<Button-1>",draw)c.bind("<Button-3>",remove)w.mainloop()# it open a windows; you can left-click and add dots in it; right-click and remove them
# example point.pyclassPoint:''' This is documentation comment. help(Point) will display this. '''def__init__(self,x=0,y=0):self.xpos=xself.ypos=ydef__str__(self):# overload print()return'Point at (%f,%f)'%(self.xpos,self.ypos)def__add__(self,other):# overloadsxpos=self.xpos+other.xposypos=self.ypos+other.yposreturnPoint(xpos,ypos)def__sub__(self,other):# overloadsimportmathdx=self.xpos-other.xposdy=self.ypos-other.yposreturnmath.sqrt(dx**2+dy**2)defdist(self):importmathreturnmath.sqrt(self.xpos**2+self.ypos**2)
# example point1.py# import Point# if point.py is in the same directory and script point1.py is independent from point.pyorigin=Point()# instanceprint(origin)p1=Point(4,4)# instancep2=Point(8,7)print(p1)
12
Point at (0.000000,0.000000)
Point at (4.000000,4.000000)
# example cpoint.pyclasscolPoint(Point):# colPoint inherits Point''' This is documentation comment. help(colPoint) will display this. '''color='black'def__init__(self,x=0,y=0,col='black'):Point.__init__(self,x,y)self.color=coldef__str__(self):return'%s colored Point at (%f,%f)'% \
(self.color,self.xpos,self.ypos)
# example point2.py# import cpoint# see above for the explanationp1=Point(5,5)rp1=colPoint(2,2,'red')
# subplotmark=['x','o','^','+','>']NR=2# number of rowsNC=3# number of columnspn=1# plot number, starting numberforrowinrange(NR):forcolinrange(NC):subplot(NR,NC,pn)a=rand(10)*pnplot(a,marker=mark[(pn+1)%5])# plot the random numbers vs tick = (n+1)5%xlabel('plot %d X'%pn)ylabel('plot %d Y'%pn)pn=pn+1# move to the 2nd plotshow()
# example 1x=arange(0,3,1)y=arange(0,3,1)gx,gy=meshgrid(x,y)print(gx)print(gy)print('-'*25)x=arange(-3*pi,3*pi,0.1)y=arange(-3*pi,3*pi,0.1)xx,yy=meshgrid(x,y)z=sin(xx)+sin(yy)imshow(z)show()
# example 2frommpl_toolkits.mplot3dimportAxes3Dax=Axes3D(figure())x=arange(-3*pi,3*pi,0.1)y=arange(-3*pi,3*pi,0.1)xx,yy=meshgrid(x,y)z=sin(xx)+sin(yy)ax.plot_surface(xx,yy,z,cmap=cm.jet,cstride=1)show()
# example 3frommpl_toolkits.mplot3dimportAxes3Dax=Axes3D(figure())phi=linspace(0,2*pi,400)x=cos(phi)y=sin(phi)z=0ax.plot(x,y,z,label='x')# circlez=sin(4*phi)# modulated in z planeax.plot(x,y,z,label='x')ax.set_xlabel('X')ax.set_ylabel('Y')ax.set_zlabel('Z')show()
# example 4frommpl_toolkits.mplot3dimportAxes3Dax=Axes3D(figure())phi=linspace(0,2*pi,100)theta=linspace(0,pi,100)x=10*outer(cos(phi),sin(theta))y=10*outer(sin(phi),sin(theta))z=10*outer(ones(size(phi)),cos(theta))ax.plot_wireframe(x,y,z,rstride=2,cstride=2)show()
An equation has any number of roots, or no roots at all.
f(x) = x^2 has a single root whereas f(x) = sin(x) has an infinite number of roots.
Visual inspection will reveal the roots (by plotting the function).
Other ways: the incremental search method, the method of bisection, and the Newton-Raphson method.
Incremental Search Method
The basic idea behind the incremental search method is simple: if f(x1) and f(x2) have opposite signs, then there is at least one root in the interval (x1; x2). If the interval is small enough, it is likely to contain a single root. Thus, the zeroes of f(x) can be detected by evaluating the function at intervals of \Delta x and looking for change in sign.
There are several potential problems with the incremental search method: it is possible to miss two closely spaced roots if the search increment \Delta x is larger than the spacing of the roots. Certain singularities of f(x) can be mistaken for roots. For example, f(x) = tan(x) changes sign at odd multiples of \pi/2, but these locations are not true zeroes.
For example, below, function root() that searches the roots of a function f(x) from x = a to x = b, incrementing it by dx.
Populating the interactive namespace from numpy and matplotlib
0.7 0.7999999999999999
1.5000000000000002 1.6000000000000003
The visual inspection will confirm. Let’s take the first function, f(x) = x^3 - 10x^2 + 5, and the inspected range, [0.0, 1.0], to plot a graph.
vector=arange(-10,20,0.05)# from numpyplot(vector,func(vector))xlabel('x-axis')ylabel('y-axis')title('Find the roots')axis([0.,2.,-1.,6.])# vert line# axvline(x = 4.,color = 'k',ls = 'dashed')# horiz lineaxhline(y=0,color='k',ls='dashed')show()
But, there is more than one root to the polynomial function, that is, f(x) = x^3 - 10x^2 + 5. Such function should have 3 roots. Indeed, another plot reveals two roots around x=0 and another one close to x=10.
vector=arange(-10,20,0.05)# from numpyplot(vector,func(vector))xlabel('x-axis')ylabel('y-axis')title('Find the roots')axis([-2.,12.,-2.,6.])# vert line# axvline(x = 4.,color = 'k',ls = 'dashed')# horiz lineaxhline(y=0,color='k',ls='dashed')show()
Method of Bisection
The method of bisection finds the root by successively halving the interval until it becomes sufficiently small.
Bisection is not the fastest method available for computing roots, but it is the most reliable. Once a root has been bracketed, bisection will always find it. The method of bisection works in the following manner:
If there is a root between x1 and x2, then f(x1)*f(x2) < 0.
Next, we compute f(x3), where x3 = (x1 + x2) = 2.
If f(x2) * f(x3) < 0, then the root must be in (x2; x3); we replace the original bound x1 by x3.
Otherwise, the root lies between x1 and x3; in this case, x3 replaces x2.
This process is repeated until the interval is reduced to a (previously) specified value, say \epsilon.
The number of bisections required to reach the prescribed limit, \epsilon, is given by equation:
n = \frac{ln(|\Delta x|)/\epsilon}{ln2}
Let’s continue with the example from above (f(x) = x^3 - 10x^2 + 5).
defbisect(f,x1,x2,epsilon=1.0e-9):f1=f(x1)f2=f(x2)iff1*f2>0.0:print('x1 and x2 are on the same side of x-axis')returnn=math.ceil(math.log(abs(x2-x1)/epsilon)/math.log(2.0))n=int(n)foriinrange(n):x3=0.5*(x1+x2)f3=f(x3)iff3==0.0:returnx3iff2*f3<0.0:x1=x3f1=f3else:x2=x3f2=f3return(x1+x2)/2.0print(bisect(func,0.70,0.8,1.0e-4))# more precise than the incremental search methodprint(bisect(func,0.70,0.8,1.0e-9))# even more decimals!
12
0.7346191406250.7346035074442625
Newton-Raphson Method
This other method is an algorithm that requires the derivative of the function to evaluate the roots. Therefore, it is usable only in problems where the derivative can be readily computed. It does not require the value at two points to start with. We start with an initial guess which is reasonably close to the true root. Then the function is approximated by its tangent line and the x-intercept of the tangent line is calculated. This value is taken as the next guess and the process is repeated. The Newton-Raphson formula is shown below.
x_{i+1} = x_i - \frac{f(x_i)}{f^{\prime}(x_i)}
Let’s run an example on the quadratic equation 2x^2 − 3x −5 = 0 and its two tangents. It can be seen that the zeros are at x = -1 and x = 2.5. By the way, the derivative of the equation is: 4x - 3
Function nr() is called twice, and we get the roots nearer to the corresponding starting values.
# the functiondeff(x):return2.0*x**2-3*x-5# the derivativedefdf(x):return4.0*x-3# the algorithmdefnr(x,tol=1.0e-9):foriinrange(30):dx=-f(x)/df(x)#print(x)x=x+dxifabs(dx)<tol:returnxprint('The roots:')print(nr(4))print(nr(0))
123
The roots:
2.5
-1.0
# the functiondeff(x):return2.0*x**2-3*x-5# the derivativedefdf(x):return4.0*x-3# the alogorithmdefnr(x,tol=1.0e-9):foriinrange(30):dx=-f(x)/df(x)print(x)x=x+dxifabs(dx)<tol:returnxprint('The iterations (nr(4):')print(nr(4))print('The iterations (nr(0):')print(nr(0))
1 2 3 4 5 6 7 8 910111213141516
The iterations (nr(4):
4
2.8461538461538463
2.528581510232886
2.500229650067341
2.5000000150663526
2.5
2.5
The iterations (nr(0):
0
-1.6666666666666667
-1.0919540229885056
-1.002295264224362
-1.0000015032391993
-1.0000000000006457
-1.0
# the functiondeff(x):return2.0*x**2-3*x-5# the derivativedefdf(x):return4.0*x-3# the plotvf=vectorize(f)x=linspace(-2,5,100)y=vf(x)# tangents at x = 3 and x = 4, using one point slope formulax1=4tg1=df(x1)*(x-x1)+f(x1)x1=3tg2=df(x1)*(x-x1)+f(x1)grid(True)plot(x,y)plot(x,tg1)plot(x,tg2)ylim([-20,40])show()
A system of m linear equations with n unknowns can be written in a matrix form and can be solved by using several standard techniques like the Gaussian elimination.
Non-homogeneous matrix equations of the form Ax = b can be solved by matrix inversion to obtain x = A^{−1}b. The system of equations
$$
\begin{align}
\ 4x + y - 2z &= 0
\ 2x - 3y + 3z &= 9
\ -6x - 2y + z &= 0
\end{align}
$$
A mathematical procedure for finding the best-fitting curve f(x) for a given set of points (x_n, y_n) by minimizing the sum of the squares of the vertical offsets of the points from the curve is called least squares fitting.
# the raw data is generated by adding random numbers (between -1 and 1) to the y coordinates# generated by y = 3∗x + 2NP=50# observationsr=2*ranf([NP])-0.5print(r)
Interpolation is the process of constructing a function f(x) from a set of data points (x_i, y_i), in the interval a < x < b that will satisfy y_i = f(x_i)
for any point in the same interval.
In other words, we find an equation with several observation by reverse engineering; we stand at the doorstep of machine and statistical learning here!
The easiest way is to construct a polynomial of degree n, such as a Newton’s interpolating polynomial, that passes through the n + 1 distinct data points. Consult the document for the mathematical demonstration. Let’s do an example.
# calculate the coefficientsfromcopyimportcopydefcoef(x,y):a=copy(y)# copy the list y to coefficient am=len(x)forkinrange(1,m):# with two loops, calculate the differencetmp=copy(a)foriinrange(k,m):tmp[i]=(a[i]-a[i-1])/(x[i]-x[i-k])a=copy(tmp)returna
x=[0,1,2,3]y=[0,3,14,39]print(coef(x,y))
1
[0, 3.0, 4.0, 1.0]
# the same can be done with a Numpy arraydefcoef(x,y):a=copy(y)m=len(x)forkinrange(1,m):a[k:m]=(a[k:m]-a[k-1])/(x[k:m]-x[k-1])returna