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

Similar documents
Lists and Loops. browse Python docs and interactive help

Numerical Integration

List Comprehensions and Simulations

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

Outline. half adders adder circuits. the while loop the for loop. Euclid s algorithm approximating π

differentiation techniques

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

Interactive Computing

turning expressions into functions symbolic substitution, series, and lambdify

Floating-Point Arithmetic

Tuples and Nested Lists

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

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

Computational Programming with Python

Physics 514 Basic Python Intro

callback, iterators, and generators

Review for Midterm Exam

High Level Parallel Processing

Outline. general information policies for the final exam

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

OOP and Scripting in Python Advanced Features

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

Divide and Conquer. playing divide and conquer. searching in a sorted list membership in a sorted list

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011

implementing the breadth-first search algorithm implementing the depth-first search algorithm

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

operator overloading algorithmic differentiation the class DifferentialNumber operator overloading

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

Problem 1 (a): List Operations

MATLAB Lecture 4. Programming in MATLAB

Welcome to MCS 360. content expectations. using g++ input and output streams the namespace std. Euclid s algorithm the while and do-while statements

Dynamic Arrays and Amortized Analysis

You Need an Interpreter! Comp Spring /28/08 L10 - An Interpreter

Programming Training. Main Points: - More Fundamental algorithms on Arrays. - Reading / Writing from files - Problem Solving

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

CSC148 Week 2. Larry Zhang

LECTURE 19. Numerical and Scientific Packages

Math 250A (Fall 2009) - Lab I: Estimate Integrals Numerically with Matlab. Due Date: Monday, September 21, INSTRUCTIONS

Functions 2/1/2017. Exercises. Exercises. Exercises. and the following mathematical appetizer is about. Functions. Functions

Exercises C-Programming

Branching and Enumeration

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015

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

Homework: Study 6.1 # 1, 5, 7, 13, 25, 19; 3, 17, 27, 53

Core Mathematics 1 Graphs of Functions

1.5 Part - 2 Inverse Relations and Inverse Functions

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections)

LECTURE 22. Numerical and Scientific Packages

Welcome to MCS 275. Course Content Prerequisites & Expectations. Scripting in Python from OOP to LAMP example: Factorization in Primes

Flow Control: Branches and loops

CSE 251 PROJECT 1. Andrew Christlieb. Monday Class AND Friday Class Abstract. Web:

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

Mathematics (JUN11MPC201) General Certificate of Education Advanced Subsidiary Examination June Unit Pure Core TOTAL

Lesson 12: The Graph of the Equation y = f(x)

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

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

COMPUTING AND DATA ANALYSIS WITH EXCEL. Numerical integration techniques

Functions with Parameters and Return Values

CS1 Lecture 3 Jan. 18, 2019

MATH2070: LAB 3: Roots of Equations

More on Lists.

Lecture 1: Hello, MATLAB!

Sequences and iteration in Python

PHCpack, phcpy, and Sphinx

Fall 2017: Numerical Methods I Assignment 1 (due Sep. 21, 2017)

managing an evolving set of connected components implementing a Union-Find data structure implementing Kruskal s algorithm

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

Outline. policies. with some potential answers... MCS 260 Lecture 19 Introduction to Computer Science Jan Verschelde, 24 February 2016

CS1 Lecture 3 Jan. 22, 2018

f( x ), or a solution to the equation f( x) 0. You are already familiar with ways of solving

LING 408/508: Computational Techniques for Linguists. Lecture 5

Math Analysis Chapter 1 Notes: Functions and Graphs

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

Final Exam Review Algebra Semester 1

Draw a diagram of an empty circular queue and describe it to the reader.

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

processing data with a database

Intelligente Datenanalyse Intelligent Data Analysis

Random Walks & Cellular Automata

S206E Lecture 13, 5/22/2016, Grasshopper Math and Logic Rules

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Random Walks & Cellular Automata

PHY224 Practical Physics I. Lecture 2

Dynamic Arrays and Amortized Analysis

Implementing Algorithms

CS1110 Lab 6 (Mar 17-18, 2015)

Finding Pi: Applications of Loops, Random Numbers, Booleans CS 8: Introduction to Computer Science, Winter 2018 Lecture #6

Areas of Planar Regions WORK SHEETS 1

61A Lecture 7. Monday, September 16

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

Python Programming Exercises 1

CS Advanced Unix Tools & Scripting

Introduction to Python Programming

Least Squares; Sequence Alignment

September 08, Graph y 2 =x. How? Is it a function? Function?

PHY224 Practical Physics I. Lecture 2

Paper Reference(s) 6672 Edexcel GCE Pure Mathematics P2 Advanced/Advanced Subsidiary Monday 20 January 2003 Morning Time: 1 hour 30 minutes

Higher order procedures procedures as types

Script language: Python Data structures

4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4.

Transcription:

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 507 Lecture 4 Mathematical, Statistical and Scientific Software Jan Verschelde, 5 September 2012 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 1 / 29

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 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 2 / 29

lists via range With range we make a list of consecutive integers: = range(5,11) >>> type(l) <type list > [5, 6, 7, 8, 9, 10] Note: range(a,b) terminates at b - 1. The default start of range is 0: >> range(5) [0, 1, 2, 3, 4] Instead of 1 as default step, use 3: >>> range(4,4+5*3,3) [4, 7, 10, 13, 16] Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 3 / 29

selecting and assigning = range(5,10) >>> len(l) 5 >>> K = L; K [5, 6, 7, 8, 9] We can assign lists as any variable. Indexing starts at 0: [2] 7 [2] = 17 Assigning to L also changes K: [5, 6, 17, 8, 9] >>> K [5, 6, 17, 8, 9] Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 4 / 29

taking slices of lists Generating 7 integers starting at 4 with step size 5: = range(4,4+7*5,5) [4, 9, 14, 19, 24, 29, 34] A slice: [2:5] [14, 19, 24] The first and last 3 numbers are selected as [:3] [4, 9, 14] [-3:] [24, 29, 34] Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 5 / 29

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 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 6 / 29

implementing a queue In a queue with first-come first-served protocol, we append items to the end and pop the front. = [].append( a ) [ a ].append( b ); L [ a, b ] >>> first = L.pop(0) >>> first a [ b ] Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 7 / 29

implementing a stack In a stack (e.g.: a pile of books), we push to the front and also pop the front. = [].insert(0, a ); L [ a ].insert(0, b ); L [ b, a ] >>> top = L.pop(0) >>> top b [ a ] Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 8 / 29

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 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 9 / 29

the insert method The first argument of insert is the index of the new element in the list. After L.insert(k,i) we have: L[k] == i. = range(0,5); L [0, 1, 2, 3, 4].insert(2, a ) [0, 1, a, 2, 3, 4].insert(len(L), b ) [0, 1, a, 2, 3, 4, b ].insert(1000, c ); L [0, 1, a, 2, 3, 4, b, c ] Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 10 / 29

popping and removing Observe the difference between pop and remove: = range(0,5); L [0, 1, 2, 3, 4].remove(0) [1, 2, 3, 4].pop(0) 1 Also their arguments have different type:.pop(2) 4 [2, 3].remove(3); L [2] Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 11 / 29

deleting elements >>> x = a ; y = b ; L = [x,y] [ a, b ] >>> del L[0] [ b ] >>> x a Although the first element a of the list is deleted, we can still refer to that a via the name x Difference with remove? The del applies to any variable. Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 12 / 29

memory locations addresses and values >>> x = 3 >>> id(x) 33568624 The machine view: 33568624 address of x 3 value of x In Python, the name x refers to the object 3. x name reference 3 object Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 13 / 29

visualizing lists from scitools.lumpy import Lumpy lumpy = Lumpy() lumpy.make_reference() L0 = [1, 4, 3] L1 = L0 L2 = L1[:-1] L1[0] = 100 lumpy.object_diagram() Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 14 / 29

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 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 15 / 29

testing membership The in operator returns True or False: = range(5,10); L [5, 6, 7, 8, 9] >>> 6 in L True >>> 3 in L False If e in L, then L[L.index(e)] == e:.index(6) 1 [1] 6 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 16 / 29

ordering lists = range(1,11) >>> import random >>> random.shuffle(l) [3, 6, 9, 10, 7, 8, 1, 4, 2, 5] >>> max(l); min(l) 10 1.reverse() [5, 2, 4, 1, 8, 7, 10, 9, 6, 3].sort() [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 17 / 29

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 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 18 / 29

for loops Computing the sum of all elements in a list L: e L e. s = 0 for e in L: s = s + e print s The indentation is important! To see how s evolves: s = 0 for e in L: s = s + e print s The second code fragment prints as many times as len(l), while the first code prints only once. Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 19 / 29

while loops The for loop is appropriate when the number of steps is fixed and known in advance. A while loop is more flexible. s = 0 for e in L: s = s + e is equivalent to s = 0; i = 0 while (i < len(l)): s = s + L[i] i = i + 1 The while loop continues as long as the condition is True. Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 20 / 29

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 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 21 / 29

the composite trapezoidal rule To approximate the integral of a function f(x) over [a, b], the trapezoidal rule is b a f(x)dx 1 (f(a) + f(b))(b a). 2 Geometrically, we approximate the area under f(x) for x [a, b] by the area of a trapezium, with base [a, b] and heights f(a) and f(b). Dividing [a, b] into n intervals of length h = (b a)/n, denote x k = a + kh, x 0 = a, x n = b, the composite trapezoidal rule is b a f(x)dx h n 1 2 (f(a) + f(b)) + h f(a + kh). k=1 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 22 / 29

evaluating functions At the command prompt $: $ python testevalfun.py give a function in x : exp(x)*sin(x) give a value for x : 1 formula exp(x)*sin(x) at 1 is 2.28735528718 The script testevalfun.py uses StringFunction of the module scitools. Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 23 / 29

the script testevalfun.py # L-4 MCS 507 Wed 5 Sep 2012 : testevalfun.py from scitools.stringfunction \ import StringFunction formula = raw_input( give a function in x : ) f = StringFunction(formula) v = input( give a value for x : ) y = f(v) print formula, formula, at, v, is, y Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 24 / 29

running comptraprule.py $ python comptraprule.py give a function in x : exp(x)*sin(x) what is left end of [a,b]? 0 what is right end of [a,b]? 2 give number of evaluations : 100 approximate integral : 5.26408379811 $ python comptraprule.py give a function in x : exp(x)*sin(x) what is left end of [a,b]? 0 what is right end of [a,b]? 2 give number of evaluations : 1000 approximate integral : 5.38346879116 $ python comptraprule.py give a function in x : exp(x)*sin(x) what is left end of [a,b]? 0 what is right end of [a,b]? 2 give number of evaluations : 10000 approximate integral : 5.39554739369 Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 25 / 29

the script comptraprule.py from scitools.stringfunction \ import StringFunction formula = raw_input( give a function in x : ) f = StringFunction(formula) a = input( what is left end of [a,b]? ) b = input( what is right end of [a,b]? ) n = input( give number of evaluations : ) h = (b-a)/float(n) s = (f(a) + f(b))/2 for i in range(1,n): s = s + f(a+i*h) s = s*h print approximate integral :, s Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 26 / 29

using scipy Romberg integration extrapolates on the composite trapezoidal rule, available in the module integrate of the package scipy. >>> from scipy.integrate import romberg >>> from math import exp, sin >>> romberg(lambda x: exp(x)*sin(x),0,2) 5.3968910090331912 With lambda we quickly define a function. Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 27 / 29

Summary + Exercises We started chapter 2 of the text book. Exercises: 1 Type L = [3, 9]; K = L; K[1] = 6 in an interactive Python session. Sketch (or use Lumpy) the relations between K and L. 2 Write a script that prompts the user for a string definition of a function f (in x), the end points of an interval [a, b] and the number n of equidistant samples in [a, b]. The script prints the maximum and minimum value of f at the n equidistant samples in [a, b]. 3 Replace the for loop in comptraprule.py by an equivalent while loop. Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 28 / 29

more exercises 4 Write a script that asks the user ( for ) two integers n and k. n n! The script prints the value of = k k!(n k)!. 5 Modify comptraprule.py so that instead of n the script prompts the user for a tolerance ǫ (e.g.: 0.001). Starting with n = 2, the number of evaluations n doubles in every step till the difference between two consecutive approximations for the integral < ǫ. The first homework collection is on Monday 10 September, at 10AM. Bring to class your answers to exercise 3 of Lecture 1; exercises 1, 2 of Lecture 2; and exercises 1, 3 of Lecture 3. Scientific Software (MCS 507) Lists and Loops 5 Sep 2012 29 / 29