callback, iterators, and generators

Size: px
Start display at page:

Download "callback, iterators, and generators"

Transcription

1 callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton function into a class 3 Newton with a Generator defining a generator with yield putting yield in newton MCS 507 Lecture 10 Mathematical, Statistical and Scientific Software Jan Verschelde, 18 September 2013 Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

2 callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton function into a class 3 Newton with a Generator defining a generator with yield putting yield in newton Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

3 Newton s method from sympy import var, Subs, exp, sin def newton(fun, drv, init, mxit=5, eps=1.0e-8): Runs Newton s method on f(x) = 0. INPUT PARAMETERS : fun a function in one variable, drv derivative of the function f, init initial guess for the root, mxit maximum number of iterations, eps accurary requirement on f(x) and on the update to x, dx. ON RETURN : the tuple (x, dx, y, fail), with: x approximation for the root, dx magnitude of last correction, y residual f(x), fail is True if the accuracy is not reached. Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

4 the body of the function def newton(fun, drv, init, mxit=5, eps=1.0e-8): "..." root = init fail = True for i in xrange(mxit): update = -fun(root)/drv(root) root = root + update residual = abs(fun(root)) if ((abs(update) <= eps) or (residual <= eps)): fail = False break return (root, abs(update), residual, fail) Observe the break: to exit the for loop when the accuracy requirement is reached. Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

5 the main function def main(): Prompts the user for an expression in x, computes its derivative and calls newton. name = var( x ) expression = input( Give an expression in x : ) derivative = expression.diff(name) # using sympy fun = lambda v: Subs(expression,(name),(v)).doit() drv = lambda v: Subs(derivative,(name),(v)).doit() guess = input( Give an initial guess : ) guess = float(guess) # force float arithmetic print newton(fun, drv, guess) main() Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

6 running newtonfun.py At the command prompt $, we type $ python newtonfun.py Give an expression in x : exp(-x**2)*sin(x) Give an initial guess : 0.3 ( e-9, , \ e-9, False) $ What if we want intermediate output? Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

7 callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton function into a class 3 Newton with a Generator defining a generator with yield putting yield in newton Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

8 a callback function def print_steps(data): Prints the content of the dictionary data and prompts the user to continue or not. result = "" for key in data.keys(): result = result + " " + key + = if ((key == dx ) or (key == res )): result = result + ( %.3e % data[key]) else: result = result + str(data[key]) print result answer = raw_input("continue? (y/n) ") return (answer == y ) Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

9 using the callback def newton(fun, drv, init, mxit=5, eps=1.0e-8, back=none): Inside the for loop: if back!= None: data = { step : i+1, x : root, dx : update, \ res : residual} proceed = back(data) if proceed!= None: if not proceed: break In main: print Newton(f, df, x0, back=print_steps) Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

10 running newtoncallback.py $ python newtoncallback.py Give an expression in x : exp(-x**2)*sin(x) Give an initial guess : 0.3 x = step = 1 \ dx = e-01 res = 7.924e-02 continue? (y/n) y x = step = 2 \ dx = 8.104e-02 res = 1.205e-03 continue? (y/n) y x = e-9 step = 3 \ dx = e-03 res = 4.085e-09 continue? (y/n) n ( e-9, , \ e-9, False) Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

11 callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton function into a class 3 Newton with a Generator defining a generator with yield putting yield in newton Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

12 object oriented programming Python is an object oriented programming language. From Object-Oriented Analysis and Design with Applications (Addison-Wesley 2007) by Grady Booch et al.: Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships. Each object has data and functional attributes. A class definition in Python usually begins with specifying the data attributes in the init method; override the str method to display an object. Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

13 a Counter class class Counter(object): Our first class stores a counter. def init (self, val=0): Sets the counter to the value val. self.count = val def str (self): Returns the string representation. return "counter is " + str(self.count) Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

14 use in Python session If the class definition is saved in classcounter.py: >>> from classcounter import Counter >>> c = Counter(3) >>> print c counter is 3 >>> str(c) counter is 3 Although we are not supposed to, we can manipulate the data attribute of an object of the class Counter directly: >>> c.count 3 >>> c.count = -4 >>> c counter is -4 Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

15 class definition continued If c is a Counter object, then typing c at the interactive prompt is the same as print c. repr (). def repr (self): Defines the representation. return self. str () def next(self): Adds one to the counter. self.count = self.count + 1 The next() method models an iterator. Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

16 a test function def test(): Performs a simple test. cnt = Counter(3) print cnt cnt.next() print cnt if name == " main ": test() Because of the last line, we run as $ python classcounter.py counter is 3 counter is 4 Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

17 callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton function into a class 3 Newton with a Generator defining a generator with yield putting yield in newton Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

18 a Newton iterator Problem: Adding a callback function to a Newton function we can see intermediate results and even stop the iteration, but the callback function remains subordinate to the main function that performs the Newton iterations. The class NewtonIterator defines an object that stores the state of all variables in a Newton iteration. Applying the next() method to an object of the class NewtonIterator executes one Newton step. Control of the execution is reverted to the consumer. Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

19 using newtoniterator >>> from newtoniterator import * >>> f = lambda x: x**2-2.0 >>> df = lambda x: 2.0*x >>> nf = NewtonIterator(f,df,2.0) >>> print nf step 0 : x = e+00, \ dx = 1.000e+00, f(x) = 2.000e+00 >>> nf.next() >>> print nf step 1 : x = e+00, \ dx = 5.000e-01, f(x) = 2.500e-01 Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

20 storing the state class NewtonIterator(object): A Newton iterator applies the Newton operator to find a solution to the equation f(x) = 0. def init (self, fun, drv, x0, n=5, eps=1.0e-8): Initializes the state of the iterator. self.step = 0 self.fun = fun self.drv = drv self.root = float(x0) self.max = n self.eps = eps self.update = 1.0 self.res = abs(fun(x0)) Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

21 printing the state def str (self): Returns the string representation of the data attributes. result = "step %d : " % self.step result = result + ("x = %.16e" % self.root) result = result + (", dx = %.3e" % self.update) result = result + (", f(x) = %.3e" % self.res) return result def repr (self): Defines the representation. return self. str () Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

22 a Newton step def next(self): Does one Newton step. self.step = self.step + 1 if (self.step > self.max): raise StopIteration\ ("only %d steps allowed" % self.max) else: work = self.root self.update = -self.fun(work)/self.drv(work) self.root = work + self.update self.update = abs(self.update) self.res = abs(self.fun(self.root)) Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

23 raising an exception If we have reached the maximum number of steps: >>> nf.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "newtoniterator.py", line 63, in next raise StopIteration("only %d steps allowed" % self.max) StopIteration: only 5 steps allowed Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

24 the stop test def accurate(self): Returns True if the accuracy requirements are satisfied. Returns False otherwise. return ((self.update <= self.eps) or (self.res <= self.eps)) Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

25 the test function def test(): Approximates the square root of 2. fun = lambda x: x**2-2.0 drv = lambda x: 2.0*x nft = NewtonIterator(fun, drv, 2.0) print nft for i in xrange(5): nft.next() print nft if nft.accurate(): break if name == " main ": test() Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

26 running newtoniterator.py $ python newtoniterator.py step 0 : x = e+00, \ dx = 1.000e+00, f(x) = 2.000e+00 step 1 : x = e+00, \ dx = 5.000e-01, f(x) = 2.500e-01 step 2 : x = e+00, \ dx = 8.333e-02, f(x) = 6.944e-03 step 3 : x = e+00, \ dx = 2.451e-03, f(x) = 6.007e-06 step 4 : x = e+00, \ dx = 2.124e-06, f(x) = 4.511e-12 Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

27 callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton function into a class 3 Newton with a Generator defining a generator with yield putting yield in newton Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

28 defining a generator with yield def counter(value=0): Maintains a counter. count = value while True: count = count + 1 yield count If saved in show_yield.py, then we can do >>> from show_yield import counter >>> mycounter = counter(3) >>> mycounter.next() 4 >>> mycounter.next() 5 >>> Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

29 using a generator def main(): Example of the use of a generator. print initializing counter... mycounter = counter(3) print incrementing counter... print mycounter.next() print incrementing counter... print mycounter.next() if name == " main ": main() Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

30 callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton function into a class 3 Newton with a Generator defining a generator with yield putting yield in newton Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

31 putting yield in newton def newton(fun, drv, init, mxit=5, eps=1.0e-8): "..." root = init fail = True for i in xrange(mxit): update = -fun(root)/drv(root) root = root + update residual = abs(fun(root)) fail = ((abs(update) > eps) and (residual > eps)) yield { step : i+1, x : root, dx : update, \ res : residual} if not fail: break Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

32 the main function def main(): Prompts the user for an expression in x, computes its derivative and calls newton. name = var( x ) expression = input( Give an expression in x : ) derivative = expression.diff(name) fun = lambda v: Subs(expression, (name),(v)).doit() drv = lambda v: Subs(derivative, (name),(v)).doit() guess = input( Give an initial guess : ) guess = float(guess) ntg = newton(fun, drv, guess) nxt = ntg.next() while nxt[ res ] > 1.0e-7: nxt = ntg.next() print nxt Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

33 Summary + Exercises Refactoring code defined by a loop as an iterator via a class gives the user more flexibility. The yield in Python is very useful. Exercises: 1 Replace the break and the enclosing for loop in the function Newton of the script newtonfun.py by an equivalent while loop. 2 Write a script that prompts the user for n, the number of iterations in a for loop that calls scipy.integrate.simps in its body. With each new call the number of function evaluations in scipy.integrate.simps doubles. Put the loop in a function which takes n as an input parameter. Add a callback function to this function. Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

34 more exercises 3 Make an iterator for the composite Simpson rule, using scipy.integrate.simps. In each step of the iterator, the total number of function evaluations doubles. 4 Write code for your own composite Simpson rule to be used in an iterator fashion. Organize the computations so that all previous function evaluations are recycled. The second homework is due on Friday 20 September, at 9AM: solve exercises 1 and 3 of Lecture 4; exercises 4 and 5 of Lecture 5; exercises 1, 2 and 5 of Lecture 6; exercises 1, 2, and 4 of Lecture 7. Scientific Software (MCS 507 L-10) callback, iterators, generators 18 September / 34

Numerical Integration

Numerical Integration Numerical Integration 1 Functions using Functions functions as arguments of other functions the one-line if-else statement functions returning multiple values 2 Constructing Integration Rules with sympy

More information

Defining Functions. turning expressions into functions. writing a function definition defining and using modules

Defining Functions. turning expressions into functions. writing a function definition defining and using modules Defining Functions 1 Lambda Functions turning expressions into functions 2 Functions and Modules writing a function definition defining and using modules 3 Computing Series Developments exploring an example

More information

differentiation techniques

differentiation techniques differentiation techniques 1 Callable Objects delayed execution of stored code 2 Numerical and Symbolic Differentiation numerical approximations for the derivative storing common code in a parent class

More information

turning expressions into functions symbolic substitution, series, and lambdify

turning expressions into functions symbolic substitution, series, and lambdify Defining Functions 1 Lambda Functions turning expressions into functions symbolic substitution, series, and lambdify 2 Functions and Modules writing a function definition defining and using modules where

More information

Lists and Loops. browse Python docs and interactive help

Lists and Loops. browse Python docs and interactive help Lists and Loops 1 Help in Python browse Python docs and interactive help 2 Lists in Python defining lists lists as queues and stacks inserting and removing membership and ordering lists 3 Loops in Python

More information

operator overloading algorithmic differentiation the class DifferentialNumber operator overloading

operator overloading algorithmic differentiation the class DifferentialNumber operator overloading operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining

More information

List Comprehensions and Simulations

List Comprehensions and Simulations List Comprehensions and Simulations 1 List Comprehensions examples in the Python shell zipping, filtering, and reducing 2 Monte Carlo Simulations testing the normal distribution the Mean Time Between Failures

More information

User Interfaces. getting arguments of the command line a command line interface to store points fitting points with polyfit of numpy

User Interfaces. getting arguments of the command line a command line interface to store points fitting points with polyfit of numpy User Interfaces 1 Command Line Interfaces getting arguments of the command line a command line interface to store points fitting points with polyfit of numpy 2 Encapsulation by Object Oriented Programming

More information

Lists and Loops. defining lists lists as queues and stacks inserting and removing membership and ordering lists

Lists and Loops. defining lists lists as queues and stacks inserting and removing membership and ordering lists Lists and Loops 1 Lists in Python defining lists lists as queues and stacks inserting and removing membership and ordering lists 2 Loops in Python for and while loops the composite trapezoidal rule MCS

More information

61A Lecture 6. Friday, September 7

61A Lecture 6. Friday, September 7 61A Lecture 6 Friday, September 7 Lambda Expressions >>> ten = 10 An expression: this one evaluates to a number >>> square = x * x Also an expression: evaluates to a function >>> square = lambda x: x *

More information

Root Finding Methods. sympy and Sage. MCS 507 Lecture 13 Mathematical, Statistical and Scientific Software Jan Verschelde, 21 September 2011

Root Finding Methods. sympy and Sage. MCS 507 Lecture 13 Mathematical, Statistical and Scientific Software Jan Verschelde, 21 September 2011 wrap Root Finding Methods 1 2 wrap MCS 507 Lecture 13 Mathematical, Statistical and Scientific Software Jan Verschelde, 21 September 2011 Root Finding Methods 1 wrap 2 wrap wrap octave-3.4.0:1> p = [1,0,2,-1]

More information

Web Clients and Crawlers

Web Clients and Crawlers Web Clients and Crawlers 1 Web Clients alternatives to web browsers opening a web page and copying its content 2 Scanning Files looking for strings between double quotes parsing URLs for the server location

More information

Tuples and Nested Lists

Tuples and Nested Lists stored in hash 1 2 stored in hash 3 and 4 MCS 507 Lecture 6 Mathematical, Statistical and Scientific Software Jan Verschelde, 2 September 2011 and stored in hash 1 2 stored in hash 3 4 stored in hash tuples

More information

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions Outline 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating

More information

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1 6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.01 Introduction to EECS I Spring

More information

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators Sven Schmit stanford.edu/~schmit/cme193 6: Classes and iterators 6-1 Contents Classes Generators and Iterators Exercises 6: Classes

More information

Abstract Data Types Chapter 1

Abstract Data Types Chapter 1 Abstract Data Types Chapter 1 Part Two Bags A bag is a basic container like a shopping bag that can be used to store collections. There are several variations: simple bag grab bag counting bag 2 Bag ADT

More information

Branching and Enumeration

Branching and Enumeration Branching and Enumeration 1 Booleans and Branching computing logical expressions computing truth tables with Sage if, else, and elif 2 Timing Python Code try-except costs more than if-else 3 Recursive

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

Unit testing with pytest and nose 1

Unit testing with pytest and nose 1 Unit testing with pytest and nose 1 Hans Petter Langtangen 1,2 1 Center for Biomedical Computing, Simula Research Laboratory 2 Department of Informatics, University of Oslo Mar 23, 2015 Contents 1 Requirements

More information

User Interfaces. MCS 507 Lecture 11 Mathematical, Statistical and Scientific Software Jan Verschelde, 16 September Command Line Interfaces

User Interfaces. MCS 507 Lecture 11 Mathematical, Statistical and Scientific Software Jan Verschelde, 16 September Command Line Interfaces User 1 2 MCS 507 Lecture 11 Mathematical, Statistical and Scientific Software Jan Verschelde, 16 September 2011 User 1 2 command line interfaces Many programs run without dialogue with user, as $ executable

More information

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1 Lecture #15: Generic Functions and Expressivity Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of

More information

PIC 16: Iterators and Generators

PIC 16: Iterators and Generators PIC 16: Iterators and Generators Assigned 10/9/2018. To be completed before lecture 10/12/2018. Intended Learning Outcomes. By the end of this preparatory assignment, students should be able to: implement

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

Fortran 90 Two Commonly Used Statements

Fortran 90 Two Commonly Used Statements Fortran 90 Two Commonly Used Statements 1. DO Loops (Compiled primarily from Hahn [1994]) Lab 6B BSYSE 512 Research and Teaching Methods The DO loop (or its equivalent) is one of the most powerful statements

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

Operator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum

Operator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum Operator Overloading 1 OOP to count Flops a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum 2 Quaternions hypercomplex numbers application in computer

More information

Interval Arithmetic. MCS 507 Lecture 29 Mathematical, Statistical and Scientific Software Jan Verschelde, 28 October 2011

Interval Arithmetic. MCS 507 Lecture 29 Mathematical, Statistical and Scientific Software Jan Verschelde, 28 October 2011 Naive Arithmetic 1 2 Naive 3 MCS 507 Lecture 29 Mathematical, Statistical and Scientific Software Jan Verschelde, 28 October 2011 Naive Arithmetic 1 2 Naive 3 an expression Naive Problem: Evaluate f(x,

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts COMP519 Web Programming Lecture 21: Python (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Functions

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

ITERATORS AND GENERATORS 10

ITERATORS AND GENERATORS 10 ITERATORS AND GENERATORS COMPUTER SCIENCE 6A July 23, 25 Iterators An iterator is an object that tracks the position in a sequence of values. It can return an element at a time, and it is only good for

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College September 25, 2017 Outline Outline 1 Chapter 4: Linked Structures and Chapter 4: Linked Structures and Outline 1 Chapter 4:

More information

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

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp. DM536 / DM550 Part 1 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm536/! RECURSION 2 Recursion a function can call other functions a function can

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Web Interfaces. the web server Apache processing forms with Python scripts Python code to write HTML

Web Interfaces. the web server Apache processing forms with Python scripts Python code to write HTML Web Interfaces 1 Python Scripts in Browsers the web server Apache processing forms with Python scripts Python code to write HTML 2 Web Interfaces for the Determinant dynamic interactive forms passing data

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

[CHAPTER] 1 INTRODUCTION 1

[CHAPTER] 1 INTRODUCTION 1 FM_TOC C7817 47493 1/28/11 9:29 AM Page iii Table of Contents [CHAPTER] 1 INTRODUCTION 1 1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing...2 1.1.1 Algorithms...2 1.1.2

More information

1 Introduction: Using a Python script to compile and plot data from Fortran modular program for Newton s method

1 Introduction: Using a Python script to compile and plot data from Fortran modular program for Newton s method 1 Introduction: Using a Python script to compile and plot data from Fortran modular program for Newton s method This week s assignment for AMS209 involves using a Python script that can compile a Fortran

More information

High Level Parallel Processing

High Level Parallel Processing High Level Parallel Processing 1 GPU computing with Maple enabling CUDA in Maple 15 stochastic processes and Markov chains 2 Multiprocessing in Python scripting in computational science the multiprocessing

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions Outline 1 Guessing Secrets functions returning functions oracles and trapdoor functions 2 anonymous functions lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

More information

Introduction to Python programming, II

Introduction to Python programming, II GC3: Grid Computing Competence Center Introduction to Python programming, II (with a hint of MapReduce) Riccardo Murri Grid Computing Competence Center, University of Zurich Oct. 10, 2012 Today s class

More information

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15 1 LECTURE 1: INTRO Introduction to Scientific Python, CME 193 Jan. 9, 2014 web.stanford.edu/~ermartin/teaching/cme193-winter15 Eileen Martin Some slides are from Sven Schmit s Fall 14 slides 2 Course Details

More information

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt. Lecture 4 while and for loops if else test Tuples Functions Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.edu Launching Python > python Quick Reminder: while Loop Example >>>

More information

Lecture #6: Higher-Order Functions at Work

Lecture #6: Higher-Order Functions at Work Lecture #6: Higher-Order Functions at Work Announcents: Free drop-in tutoring from HKN, the EECS honor society. Weekdays 11am-5pm 345 Soda or 290 Cory. For more information see hkn.eecs.berkeley.edu. A

More information

processing data with a database

processing data with a database processing data with a database 1 MySQL and MySQLdb MySQL: an open source database running MySQL for database creation MySQLdb: an interface to MySQL for Python 2 CTA Tables in MySQL files in GTFS feed

More information

Python iterators and generators

Python iterators and generators Python iterators and generators Iterators and generators Python makes good use of iterators And has a special kind of generator function that is powerful and useful We ll look at what both are And why

More information

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

Graphical User Interfaces

Graphical User Interfaces to visualize Graphical User Interfaces 1 2 to visualize MCS 507 Lecture 12 Mathematical, Statistical and Scientific Software Jan Verschelde, 19 September 2011 Graphical User Interfaces to visualize 1 2

More information

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1 Lecture #16: Generic Functions and Expressivity Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L

More information

Random Walks & Cellular Automata

Random Walks & Cellular Automata Random Walks & Cellular Automata 1 Particle Movements basic version of the simulation vectorized implementation 2 Cellular Automata pictures of matrices an animation of matrix plots the game of life of

More information

Functions and Recursion

Functions and Recursion Functions and Recursion Chapter 5 Prof. Mauro Gaspari: gaspari@cs.unibo.it Example import math def area(radius): temp = math.pi * radius**2 return temp # or def area(radius): return math.pi * radius**2

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2016 Outline Outline 1 Chapter 7: Trees Outline Chapter 7: Trees 1 Chapter 7: Trees The Binary Search Property

More information

An introduction to Scheme

An introduction to Scheme An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

Multithreaded Servers

Multithreaded Servers Multithreaded Servers 1 Serving Multiple Clients avoid to block clients with waiting using sockets and threads 2 Waiting for Data from 3 Clients running a simple multithreaded server code for client and

More information

Python Programming Exercises 1

Python Programming Exercises 1 Python Programming Exercises 1 Notes: throughout these exercises >>> preceeds code that should be typed directly into the Python interpreter. To get the most out of these exercises, don t just follow them

More information

This document describes how I implement the Newton method using Python and Fortran on the test function f(x) = (x 1) log 10 (x).

This document describes how I implement the Newton method using Python and Fortran on the test function f(x) = (x 1) log 10 (x). AMS 209 Foundations of Scientific Computing Homework 6 November 23, 2015 Cheng-Han Yu This document describes how I implement the Newton method using Python and Fortran on the test function f(x) = (x 1)

More information

Floating-Point Arithmetic

Floating-Point Arithmetic Floating-Point Arithmetic 1 Numerical Analysis a definition sources of error 2 Floating-Point Numbers floating-point representation of a real number machine precision 3 Floating-Point Arithmetic adding

More information

DM502 Programming A. Peter Schneider-Kamp.

DM502 Programming A. Peter Schneider-Kamp. DM502 Programming A Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm502/! Python & Linux Install Party Tomorrow (Tuesday, September 12) from 10 14 Fredagsbar (area south of Kantine

More information

Introduction to Python programming, II

Introduction to Python programming, II Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class

More information

7 Control Structures, Logical Statements

7 Control Structures, Logical Statements 7 Control Structures, Logical Statements 7.1 Logical Statements 1. Logical (true or false) statements comparing scalars or matrices can be evaluated in MATLAB. Two matrices of the same size may be compared,

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

Variable and Data Type I

Variable and Data Type I The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017 Variable is reserved

More information

User-Defined Function

User-Defined Function ENGR 102-213 (Socolofsky) Week 11 Python scripts In the lecture this week, we are continuing to learn powerful things that can be done with userdefined functions. In several of the examples, we consider

More information

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013 61A LECTURE 22 TAIL CALLS, ITERATORS Steven Tang and Eric Tzeng July 30, 2013 Announcements Homework 12 due Thursday, not Monday. Take the time to get started on the project instead! Almost done with Scheme

More information

SPARK-PL: Introduction

SPARK-PL: Introduction Alexey Solovyev Abstract All basic elements of SPARK-PL are introduced. Table of Contents 1. Introduction to SPARK-PL... 1 2. Alphabet of SPARK-PL... 3 3. Types and variables... 3 4. SPARK-PL basic commands...

More information

Outline. tallying the votes global and local variables call by value or call by reference. of variable length using keywords for optional arguments

Outline. tallying the votes global and local variables call by value or call by reference. of variable length using keywords for optional arguments Outline 1 Histograms tallying the votes global and local variables call by value or call by reference 2 Arguments of Functions of variable length using keywords for optional arguments 3 Functions using

More information

Programming with Python

Programming with Python Programming with Python Lecture 3: Python Functions IPEC Winter School 2015 B-IT Dr. Tiansi Dong & Dr. Joachim Köhler Python Functions arguments return obj Global vars Files/streams Function Global vars

More information

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce Lecture 38: Python CS 51G Spring 2018 Kim Bruce Announcements Test program 2 Academic Honesty Guidelines! Quiz Friday (Strings & Streams) Lecture Friday will be in lab Write searches and sorts in Python

More information

a name refers to an object side effect of assigning composite objects

a name refers to an object side effect of assigning composite objects Outline 1 Formal Languages syntax and semantics Backus-Naur Form 2 Strings, Lists, and Tuples composite data types building data structures the % operator 3 Shared References a name refers to an object

More information

Interactive Computing

Interactive Computing Interactive Computing 1 Input/Output and Complex Arithmetic interactive Python scripts complex arithmetic 2 Python Coding Style and pylint coding style static code checking with pylint 3 Programming with

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2013 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

HW DUE Floating point

HW DUE Floating point Numerical and Scientific Computing with Applications David F. Gleich CS 314, Purdue In this class: Understand the need for floating point arithmetic and some alternatives. Understand how the computer represents

More information

PHCpack, phcpy, and Sphinx

PHCpack, phcpy, and Sphinx PHCpack, phcpy, and Sphinx 1 the software PHCpack a package for Polynomial Homotopy Continuation polyhedral homotopies the Python interface phcpy 2 Documenting Software with Sphinx Sphinx generates documentation

More information

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999

Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999 Attia, John Okyere. Control Statements. Electronics and Circuit Analysis using MATLAB. Ed. John Okyere Attia Boca Raton: CRC Press LLC, 1999 1999 by CRC PRESS LLC CHAPTER THREE CONTROL STATEMENTS 3.1 FOR

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers Lecture 27 Lecture 27: Regular Expressions and Python Identifiers Python Syntax Python syntax makes very few restrictions on the ways that we can name our variables, functions, and classes. Variables names

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ Project Qualification Assessment first assessment

More information

Course Outline - COMP150. Lectures and Labs

Course Outline - COMP150. Lectures and Labs Course Outline - COMP150 Lectures and Labs 1 The way of the program 1.1 The Python programming language 1.2 What is a program? 1.3 What is debugging? 1.4 Experimental debugging 1.5 Formal and natural languages

More information

CS61A Lecture 36. Soumya Basu UC Berkeley April 15, 2013

CS61A Lecture 36. Soumya Basu UC Berkeley April 15, 2013 CS61A Lecture 36 Soumya Basu UC Berkeley April 15, 2013 Announcements HW11 due Wednesday Scheme project, contest out Our Sequence Abstraction Recall our previous sequence interface: A sequence has a finite,

More information

n Group of statements that are executed repeatedly while some condition remains true

n Group of statements that are executed repeatedly while some condition remains true Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,

More information

CME 193: Introduction to Scientific Python Lecture 1: Introduction

CME 193: Introduction to Scientific Python Lecture 1: Introduction CME 193: Introduction to Scientific Python Lecture 1: Introduction Nolan Skochdopole stanford.edu/class/cme193 1: Introduction 1-1 Contents Administration Introduction Basics Variables Control statements

More information

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

More information

High Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial

High Level Scripting. Gino Tosti University & INFN Perugia. 06/09/2010 SciNeGhe Data Analysis Tutorial High Level Scripting Part I Gino Tosti University & INFN Perugia What is a script? Scripting Languages It is a small program able to automate a repetitive and boring job; It is a list of commands that

More information

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION Instructors: Crista Lopes Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad Maybe

More information

61A Lecture 25. Friday, October 28

61A Lecture 25. Friday, October 28 61A Lecture 25 Friday, October 2 From Last Time: Adjoining to a Tree Set 5 9 7 3 9 7 11 1 7 11 Right! Left! Right! Stop! 5 9 7 3 9 7 11 1 7 11 2 From the Exam: Pruned Trees a b c d (a,b) (a,c) (a,d) pruned

More information

Graphical User Interfaces

Graphical User Interfaces Graphical User Interfaces 1 User Interfaces GUIs in Python with Tkinter object oriented GUI programming 2 Mixing Colors specification of the GUI the widget Scale 3 Simulating a Bouncing Ball layout of

More information

PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS VARIABLES, EXPRESSIONS AND STATEMENTS João Correia Lopes INESC TEC, FEUP 27 September 2018 FPRO/MIEIC/2018-19 27/09/2018 1 / 21 INTRODUCTION GOALS By the end of this class, the

More information

defining the class Parabola extending the Parabola class for visualization

defining the class Parabola extending the Parabola class for visualization Class Hierarchies 1 Points and Lines points in the plane extending the classpoint representing lines in the plane visualizing lines 2 Parabolas defining the class Parabola extending the Parabola class

More information

Running Cython. overview hello world with Cython. experimental setup adding type declarations cdef functions & calling external functions

Running Cython. overview hello world with Cython. experimental setup adding type declarations cdef functions & calling external functions Running Cython 1 Getting Started with Cython overview hello world with Cython 2 Numerical Integration experimental setup adding type declarations cdef functions & calling external functions 3 Using Cython

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Python memento TI-Smart Grids

Python memento TI-Smart Grids Python memento TI-Smart Grids Genoveva Vargas-Solar French Council of Scientific Research, LIG genoveva.vargas@imag.fr http://vargas-solar.com/data-centric-smart-everything/ * This presentation was created

More information

10.4 Linear interpolation method Newton s method

10.4 Linear interpolation method Newton s method 10.4 Linear interpolation method The next best thing one can do is the linear interpolation method, also known as the double false position method. This method works similarly to the bisection method by

More information