Lists and Loops. browse Python docs and interactive help

Size: px
Start display at page:

Download "Lists and Loops. browse Python docs and interactive help"

Transcription

1 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 for and while loops the composite trapezoidal rule MCS 507 Lecture 4 Mathematical, Statistical and Scientific Software Jan Verschelde, 4 September 2013 Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

2 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 for and while loops the composite trapezoidal rule Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

3 getting help browse documentation Launch IDLE, go to the Help menu, and to Python docs (F1) which launches a browser for the documentation. the interactive command line help >>> help() this launches the interactive help system help> topics displays a list of available topics help> LISTS shows the available help on lists help> quit >>> Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

4 getting help on a module To get help about a module, one must first import the module. For example: >>> import copy >>> help(copy) or with a relative import: >>> from copy import deepcopy >>> help(deepcopy) Printing the documentation string of a module: >>> print copy. doc Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

5 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 for and while loops the composite trapezoidal rule Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

6 lists via range With range we make a list of consecutive integers: >>> L = range(5,11) >>> type(l) <type list > >>> L [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 L-4) Lists and Loops 4 September / 34

7 selecting and assigning >>> L = 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: >>> L[2] 7 >>> L[2] = 17 Assigning to L also changes K: >>> L [5, 6, 17, 8, 9] >>> K [5, 6, 17, 8, 9] Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

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

9 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 for and while loops the composite trapezoidal rule Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

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

11 implementing a stack In a stack (e.g.: a pile of books), we push to the front and also pop the front. >>> L = [] >>> L.insert(0, a ); L [ a ] >>> L.insert(0, b ); L [ b, a ] >>> top = L.pop(0) >>> top b >>> L [ a ] Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

12 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 for and while loops the composite trapezoidal rule Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

13 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. >>> L = range(0,5); L [0, 1, 2, 3, 4] >>> L.insert(2, a ) >>> L [0, 1, a, 2, 3, 4] >>> L.insert(len(L), b ) >>> L [0, 1, a, 2, 3, 4, b ] >>> L.insert(1000, c ); L [0, 1, a, 2, 3, 4, b, c ] Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

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

15 deleting elements >>> x = a ; y = b ; L = [x,y] >>> L [ a, b ] >>> del L[0] >>> L [ 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 L-4) Lists and Loops 4 September / 34

16 memory locations addresses and values >>> x = 3 >>> id(x) The machine view: 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 L-4) Lists and Loops 4 September / 34

17 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 L-4) Lists and Loops 4 September / 34

18 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 for and while loops the composite trapezoidal rule Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

19 testing membership The in operator returns True or False: >>> L = 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: >>> L.index(6) 1 >>> L[1] 6 Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

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

21 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 for and while loops the composite trapezoidal rule Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

22 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 L-4) Lists and Loops 4 September / 34

23 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 L-4) Lists and Loops 4 September / 34

24 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 for and while loops the composite trapezoidal rule Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

25 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 L-4) Lists and Loops 4 September / 34

26 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 The script testevalfun.py uses StringFunction of the module scitools. Alternative to convert a formula to a function: lambdify of the package sympy. Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

27 the script testevalfun.py # L-4 MCS 507 Wed 4 Sep 2013 : testevalfun.py """ Using the StringFunction of scitools to make a script which prompts the user for a function. """ from scitools.stringfunction import StringFunction FORMULA = raw_input( give a function in x : ) FUN = StringFunction(FORMULA) VAL = input( give a value for x : ) RES = FUN(VAL) print formula, FORMULA, at, VAL, is, RES Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

28 using lambdify of sympy # L-4 MCS 507 Wed 4 Sep 2013 : testevalfun2.py """ Using the lambdify of sympy to make a script which prompts the user for a function. """ from sympy import lambdify FORMULA = raw_input( give a function in x : ) FUN = lambdify( x, FORMULA) VAL = input( give a value for x : ) RES = FUN(VAL) print formula, FORMULA, at, VAL, is, RES Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

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 : asterix:lec04 jan$ 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 : asterix:lec04 jan$ 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 : approximate integral : Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

30 the script comptraprule.py from scitools.stringfunction import StringFunction FORMULA = raw_input( give a function in x : ) INTEGRAND = StringFunction(FORMULA) LEFT = input( what is left end of [a,b]? ) RIGHT = input( what is right end of [a,b]? ) NBEVALS = input( give number of evaluations : ) STEP = (RIGHT - LEFT)/float(NBEVALS) SUM = (INTEGRAND(LEFT) + INTEGRAND(RIGHT))/2 for i in range(1, NBEVALS): SUM = SUM + INTEGRAND(LEFT+i*STEP) SUM = SUM*STEP print approximate integral :, SUM Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

31 comptraprule2.py uses sympy.lambdify from sympy import lambdify FORMULA = raw_input( give a function in x : ) INTEGRAND = lambdify( x, FORMULA) LEFT = input( what is left end of [a,b]? ) RIGHT = input( what is right end of [a,b]? ) NBEVALS = input( give number of evaluations : ) STEP = (RIGHT - LEFT)/float(NBEVALS) SUM = (INTEGRAND(LEFT) + INTEGRAND(RIGHT))/2 for i in range(1, NBEVALS): SUM = SUM + INTEGRAND(LEFT+i*STEP) SUM = SUM*STEP print approximate integral :, SUM Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

32 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) With lambda we quickly define a function. Calling romberg with show=true shows the extrapolation table; and tells the number of function evaluations. Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

33 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 L-4) Lists and Loops 4 September / 34

34 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 9 September, at 9AM. Bring to class your answers to exercise 3 of Lecture 1; exercises 1, 2 of Lecture 2; and exercises 1, 3 of Lecture 3. Along with a paper version, also me your scripts. Scientific Software (MCS 507 L-4) Lists and Loops 4 September / 34

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

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

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

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

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

Outline. half adders adder circuits. the while loop the for loop. Euclid s algorithm approximating π Outline 1 Digital Systems half adders adder circuits 2 Looping Constructs the while loop the for loop 3 Designing Loops Euclid s algorithm approximating π 4 Summary + Assignments MCS 260 Lecture 11 Introduction

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

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

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

More information

callback, iterators, and generators

callback, iterators, and generators 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

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

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

Divide and Conquer. playing divide and conquer. searching in a sorted list membership in a sorted list Divide and Conquer 1 Guessing a Secret playing divide and conquer 2 Binary Search searching in a sorted list membership in a sorted list 3 Bisection Search inverting a sampled function bisection search

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

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

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

MEIN 50010: Python Data Structures

MEIN 50010: Python Data Structures : Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing

More information

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

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011 Python Lists Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 5, 2011 Stéphane Vialette (LIGM UPEMLV) Python Lists October 5, 2011 1 / 31 Outline 1 Introduction 2 Methods 3 Lists as

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

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

Announcements. Project 2 due next Monday. Next Tuesday is review session; Midterm 1 on Wed., EE 129, 8:00 9:30pm

Announcements. Project 2 due next Monday. Next Tuesday is review session; Midterm 1 on Wed., EE 129, 8:00 9:30pm Project 2 due next Monday Next Tuesday is review session; Announcements Midterm 1 on Wed., EE 129, 8:00 9:30pm Project 3 to be posted Oct. 3 (next Wed) Preparing for the Midterm: Review Chapters 3-6 of

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

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

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

Computational Programming with Python

Computational Programming with Python Numerical Analysis, Lund University, 2017 1 Computational Programming with Python Lecture 1: First steps - A bit of everything. Numerical Analysis, Lund University Lecturer: Claus Führer, Alexandros Sopasakis

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

LECTURE 19. Numerical and Scientific Packages

LECTURE 19. Numerical and Scientific Packages LECTURE 19 Numerical and Scientific Packages NUMERICAL AND SCIENTIFIC APPLICATIONS As you might expect, there are a number of third-party packages available for numerical and scientific computing that

More information

Outline. general information policies for the final exam

Outline. general information policies for the final exam Outline 1 final exam on Tuesday 5 May 2015, at 8AM, in BSB 337 general information policies for the final exam 2 some example questions strings, lists, dictionaries scope of variables in functions working

More information

CSC148 Week 2. Larry Zhang

CSC148 Week 2. Larry Zhang CSC148 Week 2 Larry Zhang 1 Admin Discussion board is up (link on the course website). 2 Outline for this week Abstract Data Type Stack Queue 3 Abstract Data Type (ADT) 4 What is an abstract data type

More information

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

Math 250A (Fall 2009) - Lab I: Estimate Integrals Numerically with Matlab. Due Date: Monday, September 21, INSTRUCTIONS Math 250A (Fall 2009) - Lab I: Estimate Integrals Numerically with Matlab Due Date: Monday, September 21, 2009 4:30 PM 1. INSTRUCTIONS The primary purpose of this lab is to understand how go about numerically

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

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

LECTURE 22. Numerical and Scientific Packages

LECTURE 22. Numerical and Scientific Packages LECTURE 22 Numerical and Scientific Packages NUMERIC AND SCIENTIFIC APPLICATIONS As you might expect, there are a number of third-party packages available for numerical and scientific computing that extend

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

Physics 514 Basic Python Intro

Physics 514 Basic Python Intro Physics 514 Basic Python Intro Emanuel Gull September 8, 2014 1 Python Introduction Download and install python. On Linux this will be done with apt-get, evince, portage, yast, or any other package manager.

More information

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

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

implementing the breadth-first search algorithm implementing the depth-first search algorithm Graph Traversals 1 Graph Traversals representing graphs adjacency matrices and adjacency lists 2 Implementing the Breadth-First and Depth-First Search Algorithms implementing the breadth-first search algorithm

More information

CS1 Lecture 5 Jan. 25, 2019

CS1 Lecture 5 Jan. 25, 2019 CS1 Lecture 5 Jan. 25, 2019 HW1 due Monday, 9:00am. Notes: Do not write all the code at once before starting to test. Take tiny steps. Write a few lines test... add a line or two test... add another line

More information

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

Welcome to MCS 275. Course Content Prerequisites & Expectations. Scripting in Python from OOP to LAMP example: Factorization in Primes Welcome to MCS 275 1 About the Course Course Content Prerequisites & Expectations 2 Introduction to Programming Scripting in Python from OOP to LAMP example: Factorization in Primes 3 Summary MCS 275 Lecture

More information

OOP and Scripting in Python Advanced Features

OOP and Scripting in Python Advanced Features OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary

More information

MATLAB Lecture 4. Programming in MATLAB

MATLAB Lecture 4. Programming in MATLAB MATLAB Lecture 4. Programming in MATLAB In this lecture we will see how to write scripts and functions. Scripts are sequences of MATLAB statements stored in a file. Using conditional statements (if-then-else)

More information

Scientific Computing: Lecture 1

Scientific Computing: Lecture 1 Scientific Computing: Lecture 1 Introduction to course, syllabus, software Getting started Enthought Canopy, TextWrangler editor, python environment, ipython, unix shell Data structures in Python Integers,

More information

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 3 Jan. 18, 2019 CS1 Lecture 3 Jan. 18, 2019 Office hours for Prof. Cremer and for TAs have been posted. Locations will change check class website regularly First homework assignment will be available Monday evening, due

More information

Applications of Integration. Copyright Cengage Learning. All rights reserved.

Applications of Integration. Copyright Cengage Learning. All rights reserved. Applications of Integration Copyright Cengage Learning. All rights reserved. Area of a Region Between Two Curves Copyright Cengage Learning. All rights reserved. Objectives Find the area of a region between

More information

Python: Short Overview and Recap

Python: Short Overview and Recap Python: Short Overview and Recap Benjamin Roth CIS LMU Benjamin Roth (CIS LMU) Python: Short Overview and Recap 1 / 39 Data Types Object type Example creation Numbers (int, float) 123, 3.14 Strings this

More information

Numerical Integration

Numerical Integration Numerical Integration Numerical Integration is the process of computing the value of a definite integral, when the values of the integrand function, are given at some tabular points. As in the case of

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

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

CSE 251 PROJECT 1. Andrew Christlieb. Monday Class AND Friday Class Abstract. Web: CSE 51 PROJECT 1 Andrew Christlieb Monday Class 0-03-14 AND Friday Class 01-31-14 Abstract Web: http://www.cse.msu.edu/ cse51 Project 1 due date: (Monday Class) 0-17-14 AND (Friday Class)0-14-14, time:

More information

Lists and the for loop

Lists and the for loop Lists and the for loop Lists Lists are an ordered collection of objects Make an empty list data = [] print data [] data.append("hello!") print data ['Hello!'] data.append(5) print data ['Hello!', 5] data.append([9,

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

Review for Midterm Exam

Review for Midterm Exam Review for Midterm Exam 1 Policies and Overview midterm exam policies overview of problems, algorithms, data structures overview of discrete mathematics 2 Sample Questions on the cost functions of algorithms

More information

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

Functions 2/1/2017. Exercises. Exercises. Exercises. and the following mathematical appetizer is about. Functions. Functions Exercises Question 1: Given a set A = {x, y, z} and a set B = {1, 2, 3, 4}, what is the value of 2 A 2 B? Answer: 2 A 2 B = 2 A 2 B = 2 A 2 B = 8 16 = 128 Exercises Question 2: Is it true for all sets

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

Exercises C-Programming

Exercises C-Programming Exercises C-Programming Claude Fuhrer (claude.fuhrer@bfh.ch) 0 November 016 Contents 1 Serie 1 1 Min function.................................. Triangle surface 1............................... 3 Triangle

More information

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

Welcome to MCS 360. content expectations. using g++ input and output streams the namespace std. Euclid s algorithm the while and do-while statements Welcome to MCS 360 1 About the Course content expectations 2 our first C++ program using g++ input and output streams the namespace std 3 Greatest Common Divisor Euclid s algorithm the while and do-while

More information

Lecture 7: Python s Built-in. in Types and Basic Statements

Lecture 7: Python s Built-in. in Types and Basic Statements The University of North Carolina at Chapel Hill Spring 2002 Lecture 7: Python s Built-in in Types and Basic Statements Jan 25 1 Built-in in Data Structures: Lists A list is an ordered collection of objects

More information

Lecture 1: Hello, MATLAB!

Lecture 1: Hello, MATLAB! Lecture 1: Hello, MATLAB! Math 98, Spring 2018 Math 98, Spring 2018 Lecture 1: Hello, MATLAB! 1 / 21 Syllabus Instructor: Eric Hallman Class Website: https://math.berkeley.edu/~ehallman/98-fa18/ Login:!cmfmath98

More information

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

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing MS6021 Scientific Computing TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing Preliminary Notes on Python (v MatLab + other languages) When you enter Spyder (available on installing Anaconda),

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

COMPUTER SCIENCE LARGE PRACTICAL.

COMPUTER SCIENCE LARGE PRACTICAL. COMPUTER SCIENCE LARGE PRACTICAL Page 45 of 100 SURVEY RESULTS Approx. 1/5 of class responded; statistically significant? The majority of you have substantial experience in Java, and all have at least

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

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

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015 Numerical Methods Claus Führer Alexandros Sopasakis Centre for Mathematical Sciences Lund University Spring 2015 Preface These notes serve as a skeleton for the course. They document together with the

More information

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

You Need an Interpreter! Comp Spring /28/08 L10 - An Interpreter You Need an Interpreter! Closing the GAP Thus far, we ve been struggling to speak to computers in their language, maybe its time we spoke to them in ours How high can we rasie the level of discourse? We

More information

Core Mathematics 1 Graphs of Functions

Core Mathematics 1 Graphs of Functions Regent College Maths Department Core Mathematics 1 Graphs of Functions Graphs of Functions September 2011 C1 Note Graphs of functions; sketching curves defined by simple equations. Here are some curves

More information

Why use MATLAB? Mathematcal computations. Used a lot for problem solving. Statistical Analysis (e.g., mean, min) Visualisation (1D-3D)

Why use MATLAB? Mathematcal computations. Used a lot for problem solving. Statistical Analysis (e.g., mean, min) Visualisation (1D-3D) MATLAB(motivation) Why use MATLAB? Mathematcal computations Used a lot for problem solving Statistical Analysis (e.g., mean, min) Visualisation (1D-3D) Signal processing (Fourier transform, etc.) Image

More information

CS1110 Lab 6 (Mar 17-18, 2015)

CS1110 Lab 6 (Mar 17-18, 2015) CS1110 Lab 6 (Mar 17-18, 2015) First Name: Last Name: NetID: The lab assignments are very important and you must have a CS 1110 course consultant tell CMS that you did the work. (Correctness does not matter.)

More information

Chapter 7 Transcendental Functions

Chapter 7 Transcendental Functions Chapter 7 Transcendental Functions. Trapezoidal Rule and Simpson s Rule. Other Numerical Integration 3. Logarithmic and Eponential Functions 4. Inverse Trigonometric Functions 5. Comparing Symbolic Integration

More information

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

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

Homework: Study 6.1 # 1, 5, 7, 13, 25, 19; 3, 17, 27, 53 January, 7 Goals:. Remember that the area under a curve is the sum of the areas of an infinite number of rectangles. Understand the approach to finding the area between curves.. Be able to identify the

More information

Part 4 CLASSES AS ABSTRACT DATA TYPES AND INTERFACE IMPLEMENTATION. Data Structures and Algorithms 31632

Part 4 CLASSES AS ABSTRACT DATA TYPES AND INTERFACE IMPLEMENTATION. Data Structures and Algorithms 31632 Part 4 CLASSES AS ABSTRACT DATA TYPES AND INTERFACE IMPLEMENTATION 1 ADT ABSTRACT DATA TYPE 2 Abstract Data Type (ADT) A programmer-defined data type that specifies a set of data values and a collection

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

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science APRIL 2012 EXAMINATIONS CSC 108 H1S Instructors: Campbell Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number: Family

More information

Dynamic Arrays and Amortized Analysis

Dynamic Arrays and Amortized Analysis Yufei Tao ITEE University of Queensland As mentioned earlier, one drawback of arrays is that their lengths are fixed. This makes it difficult when you want to use an array to store a set that may continuously

More information

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points

CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points CS 1803 Pair Homework 3 Calculator Pair Fun Due: Wednesday, September 15th, before 6 PM Out of 100 points Files to submit: 1. HW3.py This is a PAIR PROGRAMMING Assignment: Work with your partner! For pair

More information

MATLAB Lecture 1. Introduction to MATLAB

MATLAB Lecture 1. Introduction to MATLAB MATLAB Lecture 1. Introduction to MATLAB 1.1 The MATLAB environment MATLAB is a software program that allows you to compute interactively with matrices. If you want to know for instance the product of

More information

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

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52 Chapter 2 Python Programming for Physicists Soon-Hyung Yook March 31, 2017 Soon-Hyung Yook Chapter 2 March 31, 2017 1 / 52 Table of Contents I 1 Getting Started 2 Basic Programming Variables and Assignments

More information

CSC326 Python Sequences i. CSC326 Python Sequences

CSC326 Python Sequences i. CSC326 Python Sequences i CSC326 Python Sequences ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 while Statement 1 3 Sequence Overview 2 4 String 2 5 Lists 4 6 Dictionary 5 7 Tuples

More information

CS1 Lecture 4 Jan. 24, 2018

CS1 Lecture 4 Jan. 24, 2018 CS1 Lecture 4 Jan. 24, 2018 First homework due Mon., 9:00am Meet specifications precisely. Functions only. Use a file editor! Don t type functions/long sections of code directly into Python interpreter.

More information

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

Fall 2017: Numerical Methods I Assignment 1 (due Sep. 21, 2017) MATH-GA 2010.001/CSCI-GA 2420.001, Georg Stadler (NYU Courant) Fall 2017: Numerical Methods I Assignment 1 (due Sep. 21, 2017) Objectives. This class is for you and you should try to get the most out of

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

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn Introduction to Machine Learning Useful tools: Python, NumPy, scikit-learn Antonio Sutera and Jean-Michel Begon September 29, 2016 2 / 37 How to install Python? Download and use the Anaconda python distribution

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

A Brief Python Tutorial

A Brief Python Tutorial Sven H. Chilton University of California - Berkeley LBL Heavy Ion Fusion Group Talk 16 August, 2007 Sven Chilton, 2007 1 Outline Why Use Python? Running Python Types and Operators Basic Statements Functions

More information

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

Finding Pi: Applications of Loops, Random Numbers, Booleans CS 8: Introduction to Computer Science, Winter 2018 Lecture #6 Finding Pi: Applications of Loops, Random Numbers, Booleans CS 8: Introduction to Computer Science, Winter 2018 Lecture #6 Ziad Matni Dept. of Computer Science, UCSB Administrative New Homework (#3) is

More information

Testing Software with Pexpect

Testing Software with Pexpect Testing Software with Pexpect 1 Testing Computer Algebra Systems testing software preparing the test suite replacing print with assert statements 2 Automating Tests with Pexpect testing SymPy in Sage with

More information

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

Mathematics (JUN11MPC201) General Certificate of Education Advanced Subsidiary Examination June Unit Pure Core TOTAL Centre Number Candidate Number For Examiner s Use Surname Other Names Candidate Signature Examiner s Initials Mathematics Unit Pure Core 2 Wednesday 18 May 2011 General Certificate of Education Advanced

More information

Problem 1 (a): List Operations

Problem 1 (a): List Operations Problem 1 (a): List Operations Task 1: Create a list, L1 = [1, 2, 3,.. N] Suppose we want the list to have the elements 1, 2, 10 range(n) creates the list from 0 to N-1 But we want the list to start from

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

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

Unit 2: Functions, Equations, & Graphs of Degree One

Unit 2: Functions, Equations, & Graphs of Degree One Date Period Unit 2: Functions, Equations, & Graphs of Degree One Day Topic 1 Relations and Functions Domain and Range 2 Graphing Linear Equations Objective 1 3 Writing Equations of Lines 4 Using the Graphing

More information

COMPUTING AND DATA ANALYSIS WITH EXCEL. Numerical integration techniques

COMPUTING AND DATA ANALYSIS WITH EXCEL. Numerical integration techniques COMPUTING AND DATA ANALYSIS WITH EXCEL Numerical integration techniques Outline 1 Quadrature in one dimension Mid-point method Trapezium method Simpson s methods Uniform random number generation in Excel,

More information

A Little Python Part 2

A Little Python Part 2 A Little Python Part 2 Introducing Programming with Python Data Structures, Program Control Outline Python and the System Data Structures Lists, Dictionaries Control Flow if, for, while Reminder - Learning

More information

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016 Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada Under Supervision of: Dr. Richard Kelley Chief Engineer, NAASIC March 6th, 2016 Science Technology Engineering

More information

Welcome to Bootcamp2015 s documentation!

Welcome to Bootcamp2015 s documentation! Welcome to Bootcamp2015 s documentation! This website (or pdf) will be home to some resources that will be useful for boot campers and instructors. Lecture notes and assignments for the econ course associated

More information

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

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017 Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Spring 2017 Outline Functions State Functions as building blocks Higher order functions Map Reduce

More information

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

Lesson 12: The Graph of the Equation y = f(x) Classwork In Module 1, you graphed equations such as 4x + y = 10 by plotting the points on the Cartesian coordinate plane that corresponded to all of the ordered pairs of numbers (x, y) that were in the

More information

CS1 Lecture 5 Jan. 26, 2018

CS1 Lecture 5 Jan. 26, 2018 CS1 Lecture 5 Jan. 26, 2018 HW1 due Monday, 9:00am. Notes: Do not write all the code at once (for Q1 and 2) before starting to test. Take tiny steps. Write a few lines test... add a line or two test...

More information

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1 Welcome to CS61A! This is a course about programming, which is the art and science of constructing artifacts ( programs ) that perform computations or interact with the physical world. To do this, we have

More information

5. ADVANCED DATA TECHNIQUES

5. ADVANCED DATA TECHNIQUES 5. ADVANCED DATA TECHNIQUES JHU Physics & Astronomy Python Workshop 2015 Lecturer: Mubdi Rahman SCIPY: FUNCTIONS YOU WANT, THE PACKAGE YOU NEED The Docs: http://docs.scipy.org/doc/scipy/reference/ L.J.

More information

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

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose

More information

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points) EECS 183 Fall 2013 Exam 1 Part 1 (80 points) Closed Book Closed Notes Closed Electronic Devices Closed Neighbor Turn off Your Cell Phones We will confiscate all electronic devices that we see including

More information