Upload
others
View
40
Download
0
Embed Size (px)
Citation preview
Introduction to Computational Models UsingPythonSlides 04
José M. Garrido C.
Department of Computer ScienceCollege of Computing and Software Engineering
Kennesaw State University
June, 2016
José M. Garrido C. Introduction to Computational Models Using Python
Lists
A list in Python is simply an ordered collection of itemseach of which can be of any type.A list is a dynamic mutable data structure and this meansthat items can be added to and deleted from it.The list data structure is the most common data sequencein Python. A sequence is a set of values identified byinteger indices.To define a list in Python, the items are written separatedby commas and in square brackets. A simple list withname vv and n items is defined as follows:
vv = [p1, p2, p3, . . . , pn]
vals = [1,2,3,4,5,6]
José M. Garrido C. Introduction to Computational Models Using Python
Indexing Lists
An individual item in the list can be referenced by using anindex, which is an integer number that indicates the relativeposition of the item in the list. The values of index numbersalways start at zero.
>>> vals = [1, 2, 3, 4, 5, 6]>>> vals[1, 2, 3, 4, 5, 6]>>> vals[0]1>>> vals[3]4>>> idx = 4>>> vals[idx]5
José M. Garrido C. Introduction to Computational Models Using Python
Indexing Lists
Using an index value of −1 is used to reference the last item ofa list and an index value of −2 is used to reference the previousto last item of the list.
>>> vals[-1]6>>> vals[-2]5
José M. Garrido C. Introduction to Computational Models Using Python
Slicing Operations
The slicing operations are used to access a sublist of the list.The colon notation is used to specify the range of index valuesof the items.
The first index value is written before the colon and the lastindex value is written after the colon. This indicates the rangeof index values from the start index value up to but not includingthe last index value specified.
>>> vals[1, 2, 3, 4, 5, 6]>>> vals[0:4][1, 2, 3, 4]>>> y = vals[2:5]>>> y[3, 4, 5]
José M. Garrido C. Introduction to Computational Models Using Python
Slicing Operations
A range of items can be updated using slicing and assignment.For example, the following command changes the values ofitems with index 0 and up to but not including the item withindex value 2.
>>> vals[0:2] = vals[1:3]>>> vals[2, 3, 3, 23.55, 5, 6]
José M. Garrido C. Introduction to Computational Models Using Python
Using slicing, the second index value can be left out andimplies that the range of index values starts from the item withthe index value specified to the last item of the list. In a similarmanner, the first index value can be left out and implies that therange of items starts with the first item of the list.
>>> vals[1:][3, 3, 23.55, 5, 6]>>> vals[:5][2, 3, 3, 23.55, 5]
José M. Garrido C. Introduction to Computational Models Using Python
Quadratic Equation
A quadratic equation is a simple mathematical model of asecond-degree equation and its solution involves complexnumbers.The goal of the solution to the problem is to compute thetwo roots of the equation.The mathematical model is:
ax2 + bx + c = 0
The given data for this problem are the values of thecoefficients of the quadratic equation: a, b, and c.Because this mathematical model is a second degreeequation, the solution consists of the value of two roots: x1and x2.
José M. Garrido C. Introduction to Computational Models Using Python
High-level flowchart for solving a quadratic equation.
José M. Garrido C. Introduction to Computational Models Using Python
Solving A Quadratic Equation with Python
1 # Program : solquad.py3 # Author : Jose M Garrido, May 17 2016.4 # Description : Compute the roots of a quadratic equation.5 # Read the value of the coefficients: a, b, and c from6 # the input console, display value of roots.78 from math import *9
10 a = input ("Enter value of coefficient a: ")11 print "Value of a: ", a12 b = input ("Enter value of coefficient b: ")13 print "Value of b: ", b14 c = input ("Enter value of coefficient c: ")15 print "Value of c: ", c1617 disc = b ** 2 - 4.0 * a * c18 print "discriminant: ", disc
José M. Garrido C. Introduction to Computational Models Using Python
Solving A Quadratic Equation with Python
19 if (disc < 0.0) :20 # complex roots21 disc = -disc22 x1r = -b/(2.0 * a)23 x1i = sqrt(disc)/(2.0 * a)24 x2r = x1r25 x2i = -x1i26 print "Complex roots "27 # print "x1r: ", x1r, " x1i: ", x1i28 x1 = complex( x1r, x1i)29 #print "x2r: ", x2r, " x2i: ", x2i30 x2 = complex (x2r, x2i)31 print "x1: ", x132 print "x2: ", x2
José M. Garrido C. Introduction to Computational Models Using Python
Solving A Quadratic Equation with Python
33 else :34 # real roots35 x1r = (-b + sqrt(disc))/(2.0 * a)36 x2r = (-b - sqrt(disc))/(2.0 * a)37 print "Real roots:"38 print "x1: ", x1r, " x2: ", x2r
José M. Garrido C. Introduction to Computational Models Using Python
Running the Python Program
The following shell commands starts the Python interpreter andit processes the program solquadra.py. The program promptsthe user for the three values of the coefficients, calculates theroots, then displays the value of the roots. Note that the rootsare complex.
$ python solquad.pyEnter value of coefficient a: 1.25Value of a: 1.25Enter value of coefficient b: 2.5Value of b: 2.5Enter value of coefficient c: 2.85Value of c: 2.85discriminant: -8.0Complex rootsx1: (-1+1.1313708499j)x2: (-1-1.1313708499j)
José M. Garrido C. Introduction to Computational Models Using Python
Multi-Level Selection
print "Testing multi-path selection in a Python script"y = 4.25x = 2.55if y > 15.50 :
x = x + 1print "x: ", x
elif y > 4.5 :x = x + 7.85print "x: ", x
elif y > 3.85 :x = y * 3.25print "x: ", x
elif y > 2.98 :x = y + z*454.7print "x: ", x
else :x = yprint "x: ", x
José M. Garrido C. Introduction to Computational Models Using Python
Repetition with Python
The following lines of code show the Python implementation ofselection. The script is stored in file test2.py.
1 # Script for testing while loop2 x = 12.353 MAX_NUM = 154 j = 05 sum = 0.06 while ( j <= MAX_NUM) :7 sum = sum + 12.58 y = x * 2.59 j = j + 3
10 print ’Value of sum: ’, sum
José M. Garrido C. Introduction to Computational Models Using Python
Summation of Input Numbers
The problem computes the summation of numeric valuesinputed from the main input device. The program is stored infile summa.py.
1 # Script for summation of input values a while loop2 # Script: summa.py34 loop_counter = 05 sum = 0.0 # initial value of accumulator variable6 innumber = input( "Type number: ")7 while innumber > 1.0 :8 sum = sum + innumber9 loop_counter = loop_counter + 1
10 print "Value of counter: ", loop_counter11 innumber = input( "Enter a number: ")
José M. Garrido C. Introduction to Computational Models Using Python
Running Summation of Input Numbers
The following output listing shows the shell commands thatstart the Python interpreter with file summa.py.
$ python summa1.pyType number: 1.5Value of counter: 1Type number: 2.55Value of counter: 2Type number: 1.055Value of counter: 3Type number: 4.12Value of counter: 4Type number: 1.25Value of counter: 5Type number: 0.0Value of sum: 10.475
José M. Garrido C. Introduction to Computational Models Using Python
Repeat-Until in Python
In Python, the repeat-until loop is not directly supported by asyntactic construct. However, it can be implemented with awhile statement.
1 # Script: test5.py2 # This script tests a loop counter in a repeat-until loop3 # implemented with a while statement45 Max_Num = 15 # max number of times to execute6 loop_counter = 1 # initial value of counter7 loop_cond = False8 while not loop_cond :9 print "Value of counter: ", loop_counter
10 loop_counter = loop_counter + 111 loop_cond = loop_counter >= Max_Num # until true
José M. Garrido C. Introduction to Computational Models Using Python
Summation Problem
1 # Script: summrep.py2 # This script computes a summation using a3 # repeat-until loop with a while statement45 sum = 0.06 loop_counter = 07 innumber = input( "Enter a number: ") # first number8 lcond = innumber <= 0.09 while not lcond:
10 sum = sum + innumber11 loop_counter = loop_counter + 112 print "Value of counter: ", loop_counter13 innumber = input( "Enter a number: ")14 lcond = innumber <= 0.01516 print "Value of sum: ", sum
José M. Garrido C. Introduction to Computational Models Using Python
Running Summation Problem
$ python summrep.pyEnter a number: 4.7Value of counter: 1Enter a number: 7.88Value of counter: 2Enter a number: 0.8Value of counter: 3Enter a number: 2.145Value of counter: 4Enter a number: 0.0Value of sum: 15.525
José M. Garrido C. Introduction to Computational Models Using Python
For Loop in Python
In Python, the simple use of the for statement uses functionrange. The first, last, and the increment values of the loopcounter are specified. The last value specified is not reallyincluded as one of the values of the loop counter. Theincrement is optional; if not included, its value is 1.
1 # Script: test6.py2 # This script tests a for loop3 x = 3.454 num = 105 sum = 0.06 for j in range(1, num) :7 sum = sum + 12.58 y = x * 2.59 print "Loop counter: ", j
1011 print "Value of sum: ", sum12 print "Value of y: ", y
José M. Garrido C. Introduction to Computational Models Using Python
For Loop in Python
$ python test6.pyLoop counter: 1Loop counter: 2Loop counter: 3Loop counter: 4Loop counter: 5Loop counter: 6Loop counter: 7Loop counter: 8Loop counter: 9Value of sum: 112.5Value of y: 8.625
José M. Garrido C. Introduction to Computational Models Using Python
Factorial Problem
The factorial operation, denoted by the symbol !, can bedefined in a general and informal manner as follows:
y ! = y (y − 1) (y − 2) (y − 3) . . . 1
For example, the factorial of 5 is:
5! = 5× 4× 3× 2× 1
A mathematical specification of the factorial function is asfollows, for y ≥ 0:
y ! ={
1 when y = 0y (y − 1)! when y > 0
José M. Garrido C. Introduction to Computational Models Using Python
Factorial Problem in Python
6 def mfact(num):11 res = 112 if num > 0:13 for num in range(num, 1, -1):14 res = res * num15 return res16 elif num == 0:17 return 118 else :19 return -12021 y = input("Enter a number to compute factorial: ")22 fy = mfact(y)23 print "Factorial is: ", fy
José M. Garrido C. Introduction to Computational Models Using Python
Running Factorial Problem in Python
$ python factp.pyEnter a number to compute factorial: 5Factorial is: 120
$ python factp.pyEnter a number to compute factorial: 0Factorial is: 1
$ python factp.pyEnter a number to compute factorial: 1Factorial is: 1
José M. Garrido C. Introduction to Computational Models Using Python
Simple Python Programs
A very simple program consists of data definitions and asequence of instructions.The script mode is normally used for writing Pythonprograms. Instructions are written into a text file using anappropriate text editor such as gedit on Linux andNotepad++ on Windows.The text file with the source code is known as a script andhas a .py extension.An instruction performs a specific manipulation orcomputation on the data, it is written as a languagestatement in the program.
José M. Garrido C. Introduction to Computational Models Using Python
Output Statement
print 〈 data_list 〉
print yprint "value of x= ", x
José M. Garrido C. Introduction to Computational Models Using Python
Input Statement
〈 var_name 〉 = input ( 〈 string_lit〉 )
y = input ("Enter value of y: ")
José M. Garrido C. Introduction to Computational Models Using Python
Simple Example
The name of this Python script is prog02.py.
# This script computes 75% of the value of yy = 34.5print "Initial value of y: ", yy = y * 0.75print "Final value of y: ", y
José M. Garrido C. Introduction to Computational Models Using Python
Running A Python Script
This script is started by invoking the python interpreter with thename of the script, prog02.py.
$ python prog02.pyInitial value of y: 34.5Final value of y: 25.875
José M. Garrido C. Introduction to Computational Models Using Python
Example with Input Statement
# This script computes 75% of the value of yy = input ("Enter initial value of y: ")print "Initial value of y: ", yy = y * 0.75print "Final value of y: ", y
José M. Garrido C. Introduction to Computational Models Using Python
Function Definition
The general syntactical form of a function definition is:
def function_name ( [parameters] ) :[ local declarations ][ executable language statements ]
The relevant internal documentation of the function definition isdescribed in one or more lines of comments, which begins withthe characters (""") and ends with (""").
def show_message () :"""This function displays a messageon the screen.
"""print("Computing data")
José M. Garrido C. Introduction to Computational Models Using Python
Definition and Function Call
2 # Program : shmesp.py3 # Author : Jose M Garrido, May 17 2016.4 # Description : Define and call a simple function.56 def show_message():7 """8 This function displays a message9 on the screen
10 """11 print "Computing results ..... "1213 y = input("Enter a number: ")14 sqy = y * y15 show_message()16 print "square of the number is: ", sqy
José M. Garrido C. Introduction to Computational Models Using Python
Questions?
José M. Garrido C. Introduction to Computational Models Using Python