Introduction to Computational Models Using Python

Similar documents
SIMPLE I/O WITH PYTHON

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Flow Control: Branches and loops

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

Test #2 October 8, 2015

Problem 1 (a): List Operations

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Algorithms and Data Structures

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Computing with Numbers

Some material adapted from Upenn cmpe391 slides and other sources

Statements 2. a operator= b a = a operator b

Introduction to Computer Programming for Non-Majors

Object Oriented Programming Using C++ Mathematics & Computing IET, Katunayake

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Multi-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic

PROGRAM DESIGN TOOLS. Algorithms, Flow Charts, Pseudo codes and Decision Tables. Designed by Parul Khurana, LIECA.

Introduction to Computer Programming for Non-Majors

Python lab session 1

ECE 202 LAB 3 ADVANCED MATLAB

Lab 5a Shell Script Lab 4 Using Arithmetic Operators in shell script

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Lists How lists are like strings

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

Fundamentals of Programming (Python) Getting Started with Programming

Introduction to MATLAB

Core Mathematics 1 Transformations of Graphs

Sequences and Loops. Indices: accessing characters in a string. Old friend: isvowel. Motivation: How to count the number of vowels in a word?

Conditional Expressions and Decision Statements

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Basic Syntax - First Program 1

Arrays Structured data Arrays What is an array?

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Python. Department of Computer Science And Engineering. European University Cyprus

Programming to Python

CSI33 Data Structures

Visualize ComplexCities

GEOMETRIC MODELS WITH PYTHON

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Lecture 04 FUNCTIONS AND ARRAYS

At full speed with Python

IMPLEMENTING SCL PROGRAMS. Using Codeblocks

Variable and Data Type 2

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

11.3 Function Prototypes

PSEUDOCODE AND FLOWCHARTS. Introduction to Programming

Top bar items. Current folder should be shown. Command Window This has the the prompt >>

Chapter 2 Writing Simple Programs

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

User-Defined Function

Computational Modelling 102 (Scientific Programming) Tutorials

CS111: PROGRAMMING LANGUAGE II

YOLOP Language Reference Manual

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

The current topic: Python. Announcements. Python. Python

Here n is a variable name. The value of that variable is 176.

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

18.1. CS 102 Unit 18. Python. Mark Redekopp

Introduction to Programming with Python: overview

Functions and Recursion

Part III Appendices 165

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Python for ArcGIS. Lab 1.

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

Fundamentals of the J Programming Language

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Lab 5: Repetition Structures This lab accompanies Chapter 5 of Starting Out with Programming Logic & Design.

Chapter 5 : Informatics practices. Conditional & Looping Constructs. Class XI ( As per CBSE Board)

Physics 326G Winter Class 6

[301] JSON. Tyler Caraza-Harter

Part 1 Your First Function

HW DUE Floating point

Computer Vision. Matlab

Introduction to Computer Programming for Non-Majors

DM536 Introduction to Programming. Peter Schneider-Kamp.

Programming with Python

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Dr Richard Greenaway

Question 1. [5 points] Circle and briefly explain the error(s) in the following code:

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Fundamentals of Programming (Python) Control Structures. Sina Sajadmanesh Sharif University of Technology Fall 2017

Computational Programming with Python

ENGR 102 Engineering Lab I - Computation

Variable and Data Type I

Getting Started with Python

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Scientific Computing: Lecture 1

A Look Back at Arithmetic Operators: the Increment and Decrement

USING THE OOSIML/JAVA. With a Terminal Window

CS1110 Lab 6 (Mar 17-18, 2015)

TREES AND ORDERS OF GROWTH 7

1 Short Answer (5 Points Each)

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Introduction to Programming with Python

MAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB

Transcription:

Introduction to Computational Models Using Python Slides 04 Department of Computer Science College of Computing and Software Engineering Kennesaw State University June, 2016

Lists A list in Python is simply an ordered collection of items each of which can be of any type. A list is a dynamic mutable data structure and this means that items can be added to and deleted from it. The list data structure is the most common data sequence in Python. A sequence is a set of values identified by integer indices. To define a list in Python, the items are written separated by commas and in square brackets. A simple list with name vv and n items is defined as follows: vals = [1,2,3,4,5,6] vv = [p 1, p 2, p 3,..., p n ]

Indexing Lists An individual item in the list can be referenced by using an index, which is an integer number that indicates the relative position of the item in the list. The values of index numbers always 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

Indexing Lists Using an index value of 1 is used to reference the last item of a list and an index value of 2 is used to reference the previous to last item of the list. >>> vals[-1] 6 >>> vals[-2] 5

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 values of the items. The first index value is written before the colon and the last index value is written after the colon. This indicates the range of index values from the start index value up to but not including the 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]

Slicing Operations A range of items can be updated using slicing and assignment. For example, the following command changes the values of items with index 0 and up to but not including the item with index value 2. >>> vals[0:2] = vals[1:3] >>> vals [2, 3, 3, 23.55, 5, 6]

Using slicing, the second index value can be left out and implies that the range of index values starts from the item with the index value specified to the last item of the list. In a similar manner, the first index value can be left out and implies that the range 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]

Quadratic Equation A quadratic equation is a simple mathematical model of a second-degree equation and its solution involves complex numbers. The goal of the solution to the problem is to compute the two roots of the equation. The mathematical model is: ax 2 + bx + c = 0 The given data for this problem are the values of the coefficients of the quadratic equation: a, b, and c. Because this mathematical model is a second degree equation, the solution consists of the value of two roots: x 1 and x 2.

High-level flowchart for solving a quadratic equation.

Solving A Quadratic Equation with Python 1 # Program : solquad.py 3 # Author : Jose M Garrido, May 17 2016. 4 # Description : Compute the roots of a quadratic equ 5 # Read the value of the coefficients: a, b, and c 6 # the input console, display value of roots. 7 8 from math import * 9 10 a = input ("Enter value of coefficient a: ") 11 print "Value of a: ", a 12 b = input ("Enter value of coefficient b: ") 13 print "Value of b: ", b 14 c = input ("Enter value of coefficient c: ") 15 print "Value of c: ", c 16 17 disc = b ** 2-4.0 * a * c 18 print "discriminant: ", disc

Solving A Quadratic Equation with Python 19 if (disc < 0.0) : 20 # complex roots 21 disc = -disc 22 x1r = -b/(2.0 * a) 23 x1i = sqrt(disc)/(2.0 * a) 24 x2r = x1r 25 x2i = -x1i 26 print "Complex roots " 27 # print "x1r: ", x1r, " x1i: ", x1i 28 x1 = complex( x1r, x1i) 29 #print "x2r: ", x2r, " x2i: ", x2i 30 x2 = complex (x2r, x2i) 31 print "x1: ", x1 32 print "x2: ", x2

Solving A Quadratic Equation with Python 33 else : 34 # real roots 35 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

Running the Python Program The following shell commands starts the Python interpreter and it processes the program solquadra.py. The program prompts the user for the three values of the coefficients, calculates the roots, then displays the value of the roots. Note that the roots are complex. $ python solquad.py Enter value of coefficient a: 1.25 Value of a: 1.25 Enter value of coefficient b: 2.5 Value of b: 2.5 Enter value of coefficient c: 2.85 Value of c: 2.85 discriminant: -8.0 Complex roots x1: (-1+1.1313708499j) x2: (-1-1.1313708499j)

Multi-Level Selection print "Testing multi-path selection in a Python script" y = 4.25 x = 2.55 if y > 15.50 : x = x + 1 print "x: ", x elif y > 4.5 : x = x + 7.85 print "x: ", x elif y > 3.85 : x = y * 3.25 print "x: ", x elif y > 2.98 : x = y + z*454.7 print "x: ", x else : x = y print "x: ", x

Repetition with Python The following lines of code show the Python implementation of selection. The script is stored in file test2.py. 1 # Script for testing while loop 2 x = 12.35 3 MAX_NUM = 15 4 j = 0 5 sum = 0.0 6 while ( j <= MAX_NUM) : 7 sum = sum + 12.5 8 y = x * 2.5 9 j = j + 3 10 print Value of sum:, sum

Summation of Input Numbers The problem computes the summation of numeric values inputed from the main input device. The program is stored in file summa.py. 1 # Script for summation of input values a while loop 2 # Script: summa.py 3 4 loop_counter = 0 5 sum = 0.0 # initial value of accumulator variable 6 innumber = input( "Type number: ") 7 while innumber > 1.0 : 8 sum = sum + innumber 9 loop_counter = loop_counter + 1 10 print "Value of counter: ", loop_counter 11 innumber = input( "Enter a number: ")

Running Summation of Input Numbers The following output listing shows the shell commands that start the Python interpreter with file summa.py. $ python summa1.py Type number: 1.5 Value of counter: 1 Type number: 2.55 Value of counter: 2 Type number: 1.055 Value of counter: 3 Type number: 4.12 Value of counter: 4 Type number: 1.25 Value of counter: 5 Type number: 0.0 Value of sum: 10.475

Repeat-Until in Python In Python, the repeat-until loop is not directly supported by a syntactic construct. However, it can be implemented with a while statement. 1 # Script: test5.py 2 # This script tests a loop counter in a repeat-until 3 # implemented with a while statement 4 5 Max_Num = 15 # max number of times to execute 6 loop_counter = 1 # initial value of counter 7 loop_cond = False 8 while not loop_cond : 9 print "Value of counter: ", loop_counter 10 loop_counter = loop_counter + 1 11 loop_cond = loop_counter >= Max_Num # until true

Summation Problem 1 # Script: summrep.py 2 # This script computes a summation using a 3 # repeat-until loop with a while statement 4 5 sum = 0.0 6 loop_counter = 0 7 innumber = input( "Enter a number: ") # first number 8 lcond = innumber <= 0.0 9 while not lcond: 10 sum = sum + innumber 11 loop_counter = loop_counter + 1 12 print "Value of counter: ", loop_counter 13 innumber = input( "Enter a number: ") 14 lcond = innumber <= 0.0 15 16 print "Value of sum: ", sum

Running Summation Problem $ python summrep.py Enter a number: 4.7 Value of counter: 1 Enter a number: 7.88 Value of counter: 2 Enter a number: 0.8 Value of counter: 3 Enter a number: 2.145 Value of counter: 4 Enter a number: 0.0 Value of sum: 15.525

For Loop in Python In Python, the simple use of the for statement uses function range. The first, last, and the increment values of the loop counter are specified. The last value specified is not really included as one of the values of the loop counter. The increment is optional; if not included, its value is 1. 1 # Script: test6.py 2 # This script tests a for loop 3 x = 3.45 4 num = 10 5 sum = 0.0 6 for j in range(1, num) : 7 sum = sum + 12.5 8 y = x * 2.5 9 print "Loop counter: ", j 10 11 print "Value of sum: ", sum 12 print "Value of y: ", y

For Loop in Python $ python test6.py Loop counter: 1 Loop counter: 2 Loop counter: 3 Loop counter: 4 Loop counter: 5 Loop counter: 6 Loop counter: 7 Loop counter: 8 Loop counter: 9 Value of sum: 112.5 Value of y: 8.625

Factorial Problem The factorial operation, denoted by the symbol!, can be defined 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 as follows, for y 0: { 1 when y = 0 y! = y (y 1)! when y > 0

Factorial Problem in Python 6 def mfact(num): 11 res = 1 12 if num > 0: 13 for num in range(num, 1, -1): 14 res = res * num 15 return res 16 elif num == 0: 17 return 1 18 else : 19 return -1 20 21 y = input("enter a number to compute factorial: ") 22 fy = mfact(y) 23 print "Factorial is: ", fy

Running Factorial Problem in Python $ python factp.py Enter a number to compute factorial: 5 Factorial is: 120 $ python factp.py Enter a number to compute factorial: 0 Factorial is: 1 $ python factp.py Enter a number to compute factorial: 1 Factorial is: 1

Simple Python Programs A very simple program consists of data definitions and a sequence of instructions. The script mode is normally used for writing Python programs. Instructions are written into a text file using an appropriate text editor such as gedit on Linux and Notepad++ on Windows. The text file with the source code is known as a script and has a.py extension. An instruction performs a specific manipulation or computation on the data, it is written as a language statement in the program.

Output Statement print data_list print y print "value of x= ", x

Input Statement var_name = input ( string_lit ) y = input ("Enter value of y: ")

Simple Example The name of this Python script is prog02.py. # This script computes 75% of the value of y y = 34.5 print "Initial value of y: ", y y = y * 0.75 print "Final value of y: ", y

Running A Python Script This script is started by invoking the python interpreter with the name of the script, prog02.py. $ python prog02.py Initial value of y: 34.5 Final value of y: 25.875

Example with Input Statement # This script computes 75% of the value of y y = input ("Enter initial value of y: ") print "Initial value of y: ", y y = y * 0.75 print "Final value of y: ", y

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 is described in one or more lines of comments, which begins with the characters (""") and ends with ("""). def show_message () : """ This function displays a message on the screen. """ print("computing data")

Definition and Function Call 2 # Program : shmesp.py 3 # Author : Jose M Garrido, May 17 2016. 4 # Description : Define and call a simple function. 5 6 def show_message(): 7 """ 8 This function displays a message 9 on the screen 10 """ 11 print "Computing results... " 12 13 y = input("enter a number: ") 14 sqy = y * y 15 show_message() 16 print "square of the number is: ", sqy

Questions?