List Comprehensions and Simulations

Size: px
Start display at page:

Download "List Comprehensions and Simulations"

Transcription

1 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 (MTBF) problem MCS 507 Lecture 5 Mathematical, Statistical and Scientific Software Jan Verschelde, 6 September 2013 Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

2 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 (MTBF) problem Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

3 using for in lists Computing the square of some numbers: >>> L = range(5) >>> L [0, 1, 2, 3, 4] >>> [x**2 for x in L] [0, 1, 4, 9, 16] The general syntax of a list comprehension is [ expression(x) for x in somelist ] Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

4 range versus xrange With range we create a list. So: >>> L = [x**2 for x in range(0,5)] 1 creates the list [0, 1, 2, 3, 4] 2 lets x run through that list. If we are interested only in the end result, then generating [0, 1, 2, 3, 4] is wasteful. With xrange, the element in the range is generated only when needed and the entire range is not stored. >>> L = [x**2 for x in xrange(0,5)] >>> L [0, 1, 4, 9, 16] Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

5 listing all characters Every character is encoded by one byte: >>> ord( a ) 97 >>> chr(97) a To list all characters: >>> a = ord( a ) >> z = ord( z ) >>> [chr(i) for i in xrange(a,z+1)] [ a, b, c,.., y, z ] Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

6 string representations The str() function is defined on a list: >>> L = range(5) >>> s = str(l) >>> L [0, 1, 2, 3, 4] >>> s [0, 1, 2, 3, 4] >>> eval(s) [0, 1, 2, 3, 4] We may prompt for a list: >>> K = input( enter a list : ) enter a list : [1,2,3] >>> K [1, 2, 3] Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

7 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 (MTBF) problem Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

8 zipping lists >>> L = range(5) >>> a = ord( a ); a 97 >>> chr(a) a The name a refers to the string a, which is encoded by the byte with value 97. >>> K = [chr(i) for i in xrange(a,a+5)] >>> K [ a, b, c, d, e ] >>> L [0, 1, 2, 3, 4] >>> Z = [[a,b] for a, b in zip(l,k)] >>> Z [[0, a ], [1, b ], [2, c ], [3, d ], [4, e ]] Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

9 lambda expressions We can make short functions with lambda: >>> f = lambda x: x**2 >>> type(f) <type function > >>> f(3) 9 Lambda expressions are used in other functions, for example: numerical integration, and are in list processing functions. Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

10 filtering lists Find all numbers between 0 and 99 that are divisible by 3; and that have 2 as a last digit. First we define a filter function: >>> f = lambda x: x % 3 == 0 and x % 10 == 2 >>> f(12) True >>> f(11) False Then we apply the filter f to a list: >>> L = range(100) >>> F = filter(f,l) >>> F [12, 42, 72] Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

11 reducing lists To compute the sum of the elements in a list L: sum(l). The factorial of 10 is : >>> L = range(1,11) >>> reduce(lambda x,y: x*y, L) The reduce() calculated (..((1 2) 3)..) 10 The function given as argument to reduce() must take two elements on input, return one single element. reduce() repeatedly replaces the first two elements of the list by the result of the function, applied to those first two elements, until only one element in the list is left. Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

12 the Horner form The Horner form of a polynomial is 2x 2 8x + 3 = ((2x 8)x + 3. To evaluate a dense polynomial of degree d we need d additions and d multiplications. We apply reduce() to a polynomial with integer coefficients stored in a list: >>> c = [2, -8, 3] >>> h = lambda x,y: ( + str(x) + *x \... + ( %+d % y) + ) >>> h(2,-8) (2*x-8) >>> h(2,8) (2*x+8) >>> reduce(h,c) ((2*x-8)*x+3) Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

13 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 (MTBF) problem Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

14 testing random.gauss The normal distribution is provided by the function gauss in the builtin module random of Python. To test gauss, given mean µ and standard deviation σ, we generate a number n of samples, and for the n samples, we compute the mean µ and standard deviation σ. For large enough n, the computed µ µ and σ σ. We count the number of samples within the standard deviation of the mean, that is: inside [σ µ,σ + µ]. Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

15 running testgauss.py $ python testgauss.py testing the normal distribution give the mean : 5 give the standard deviation : 2 give the number of samples : average of samples : standard deviation : #samples in [3.00,7.00] : 6856 smallest sample : largest sample : Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

16 the script testgauss.py from random import gauss from math import sqrt print testing the normal distribution MU = input( give the mean : ) SIGMA = input( give the standard deviation : ) DIM = input( give the number of samples : ) L = [gauss(mu, SIGMA) for i in xrange(dim)] Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

17 testgauss.py continued AVG = sum(l)/dim SQR = [(e - AVG)**2 for e in L] STD = sqrt(sum(sqr)/dim) A = MU - SIGMA B = MU + SIGMA F = filter(lambda x: A < x < B, L) print average of samples :, AVG print standard deviation :, STD print #samples in [%.2f, %.2f] : %d % (A, B, len(f)) print smallest sample :, min(l) print largest sample :, max(l) Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

18 deprecated-lambda in map/filter pylint warns about F = filter(lambda x: A < x < B, L) In particular: W: 26, 4: Used builtin function filter (bad-builtin) W: 26, 4: map/filter on lambda could be replaced by comprehension (deprecated-lambda) A better construction (if only interested in len(f)) is TEST = lambda x: A < x < B F = [TEST(e) for e in L] print sum(f) Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

19 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 (MTBF) problem Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

20 mean time between failures The Mean Time Between Failures (MTBF) problem asks for the expected life span of a product made of components. Every component is critical. The multi-component product fails as soon as one of its components fails. For every component we assume that the life span follows a known normal distribution, given by µ and σ. For example, consider 3 components with respective means 11, 12, 13 and corresponding standard deviations 1, 2, 3. Running 10,000 simulations, we compute the average life span of the composite product. Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

21 the script mtbf.py from random import gauss from math import sqrt (MEAN1, SIGMA1) = (11, 1) (MEAN2, SIGMA2) = (12, 2) (MEAN3, SIGMA3) = (13, 3) DIM = L1 = [gauss(mean1, SIGMA1) for i in xrange(dim)] L2 = [gauss(mean2, SIGMA2) for i in xrange(dim)] L3 = [gauss(mean3, SIGMA3) for i in xrange(dim)] L = [min(x, y, z) for x, y, z in zip(l1, L2, L3)] AVG = sum(l)/dim SQR = [(e - AVG)**2 for e in L] STD = sqrt(sum(sqr)/dim) print average of samples :, AVG print standard deviation :, STD Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

22 running mtbf.py $ python mtbf.py average of samples : standard deviation : $ Some extensions to the example: product fails if two of its components fail; or product fails if component one and two both fail or if component three fails. Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

23 Summary + Exercises We covered more of chapter 2 of the text book. Exercises: 1 Make a list of all the digits of math.pi. 2 A sieve method to find all primes in a range 2 to n removes all multiples of 2, 3, 5, etc. Apply the filter function to sieve for all primes between 2 and Use list comprehensions to generate points (x, y) uniformly distributed on the circle: x 2 + y 2 = 1. Use random.uniform(0,2*math.pi) for random angles t: x = cos(t), y = sin(t), cos 2 (t) + sin 2 (t) = 1. Scientific Software (MCS 507 L-5) Lists Comprehensions and Simulations 6 September / 24

24 more exercises 4 Generate a sequence of cubes x 3, for x ranging over all natural numbers between 1 and 70. To determine which cubes are squares of natural numbers, take the square root of those cubes and select those numbers which have a natural number as their square root. 5 Extend mtbf.py so that it works for any number of components, prompting the user for a list of means and a list of corresponding standard deviations. 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-5) Lists Comprehensions and Simulations 6 September / 24

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

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

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

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

Module 10: Imperative Programming, Modularization, and The Future

Module 10: Imperative Programming, Modularization, and The Future Module 10: Imperative Programming, Modularization, and The Future If you have not already, make sure you Read How to Design Programs Sections 18. 1 CS 115 Module 10: Imperative Programming, Modularization,

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

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

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

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

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

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

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

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

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

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

Module 7 Highlights. Mastered Reviewed. Sections ,

Module 7 Highlights. Mastered Reviewed. Sections , Sections 5.3 5.6, 6.1 6.6 Module 7 Highlights Andrea Hendricks Math 0098 Pre-college Algebra Topics Degree & leading coeff. of a univariate polynomial (5.3, Obj. 1) Simplifying a sum/diff. of two univariate

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

Introduction to Programming

Introduction to Programming Introduction to Programming Python Lab 3: Arithmetic PythonLab3 lecture slides.ppt 16 October 2018 Ping Brennan (p.brennan@bbk.ac.uk) 1 Getting Started Create a new folder in your disk space with the name

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Python Lab 3: Arithmetic PythonLab3 lecture slides.ppt 26 January 2018 Ping Brennan (p.brennan@bbk.ac.uk) 1 Getting Started Create a new folder in your disk space with the name

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

Function. Mathematical function and C+ + function. Input: arguments. Output: return value

Function. Mathematical function and C+ + function. Input: arguments. Output: return value Lecture 9 Function Mathematical function and C+ + function Input: arguments Output: return value Sqrt() Square root function finds the square root for you It is defined in the cmath library, #include

More information

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

Python Lists: Example 1: >>> items=[apple, orange,100,25.5] >>> items[0] 'apple' >>> 3*items[:2] Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.

More information

7COM1023 Programming Paradigms

7COM1023 Programming Paradigms 7COM Programming Paradigms Practical Answers Expressions We will commence by typing in some expressions to familiarise ourselves with the environment.. Type in the following and evaluate them by pressing

More information

Introduction to Scientific Computing with Python, part two.

Introduction to Scientific Computing with Python, part two. Introduction to Scientific Computing with Python, part two. M. Emmett Department of Mathematics University of North Carolina at Chapel Hill June 20 2012 The Zen of Python zen of python... fire up python

More information

Advanced features of the Calculate signal tool

Advanced features of the Calculate signal tool Advanced features of the Calculate signal tool Case study: how to us the advanced features of the Calculate signal tool? 1 The calculate signal tool The calculate signal tool is one of the most useful

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

ENGR (Socolofsky) Week 02 Python scripts

ENGR (Socolofsky) Week 02 Python scripts ENGR 102-213 (Socolofsky) Week 02 Python scripts Listing for script.py 1 # data_types.py 2 # 3 # Lecture examples of using various Python data types and string formatting 4 # 5 # ENGR 102-213 6 # Scott

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

MATLAB NOTES. Matlab designed for numerical computing. Strongly oriented towards use of arrays, one and two dimensional.

MATLAB NOTES. Matlab designed for numerical computing. Strongly oriented towards use of arrays, one and two dimensional. MATLAB NOTES Matlab designed for numerical computing. Strongly oriented towards use of arrays, one and two dimensional. Excellent graphics that are easy to use. Powerful interactive facilities; and programs

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

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

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

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have

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

MATH 2650/ Intro to Scientific Computation - Fall Lab 1: Starting with MATLAB. Script Files

MATH 2650/ Intro to Scientific Computation - Fall Lab 1: Starting with MATLAB. Script Files MATH 2650/3670 - Intro to Scientific Computation - Fall 2017 Lab 1: Starting with MATLAB. Script Files Content - Overview of Course Objectives - Use of MATLAB windows; the Command Window - Arithmetic operations

More information

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

Outline. policies. with some potential answers... MCS 260 Lecture 19 Introduction to Computer Science Jan Verschelde, 24 February 2016 Outline 1 midterm exam on Friday 26 February 2016 policies 2 questions with some potential answers... MCS 260 Lecture 19 Introduction to Computer Science Jan Verschelde, 24 February 2016 Intro to Computer

More information

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value 1 Number System Introduction In this chapter, we will study about the number system and number line. We will also learn about the four fundamental operations on whole numbers and their properties. Natural

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

Computer Programming in MATLAB

Computer Programming in MATLAB Computer Programming in MATLAB Prof. Dr. İrfan KAYMAZ Atatürk University Engineering Faculty Department of Mechanical Engineering What is a computer??? Computer is a device that computes, especially a

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

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

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

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

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

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions. COMP1730/COMP6730 Programming for Scientists Data: Values, types and expressions. Lecture outline * Data and data types. * Expressions: computing values. * Variables: remembering values. What is data?

More information

Computational Methods of Scientific Programming. Lecturers Thomas A Herring Chris Hill

Computational Methods of Scientific Programming. Lecturers Thomas A Herring Chris Hill 12.010 Computational Methods of Scientific Programming Lecturers Thomas A Herring Chris Hill Review of Lecture 2 Examined computer hardware Computer basics and the main features of programs Program design:

More information

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions 0 Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x 2 x {1...5}} The set {1,4,9,16,25}

More information

Lecture 1 August 9, 2017

Lecture 1 August 9, 2017 Programming in Haskell S P Suresh http://www.cmi.ac.in/~spsuresh Lecture 1 August 9, 2017 Administrative Mondays and Wednesdays at 9.10 am at Lecture Hall 6 Evaluation: Quizzes, 4 5 programming assignments,

More information

CS1 Lecture 4 Jan. 23, 2019

CS1 Lecture 4 Jan. 23, 2019 CS1 Lecture 4 Jan. 23, 2019 First graded discussion sections this week yesterday/today 10 DS assignments worth 2 points each everyone gets one free 2-pointer. I.e. your lowest DS grade will be replaced

More information

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

More information

MATLAB: The Basics. Dmitry Adamskiy 9 November 2011

MATLAB: The Basics. Dmitry Adamskiy 9 November 2011 MATLAB: The Basics Dmitry Adamskiy adamskiy@cs.rhul.ac.uk 9 November 2011 1 Starting Up MATLAB Windows users: Start up MATLAB by double clicking on the MATLAB icon. Unix/Linux users: Start up by typing

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

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

Python for Finance. Introduction and Basics of Python. Andras Niedermayer

Python for Finance. Introduction and Basics of Python. Andras Niedermayer Python for Finance Introduction and Basics of Python Andras Niedermayer Outline 1 Introduction 2 Why Python? 3 Python installation and environments 4 First Steps in Python 5 Variables 6 Basic Operations

More information

Scientific Computing with MATLAB

Scientific Computing with MATLAB Scientific Computing with MATLAB Dra. K.-Y. Daisy Fan Department of Computer Science Cornell University Ithaca, NY, USA UNAM IIM 2012 2 Focus on computing using MATLAB Computer Science Computational Science

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

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

Computer Programming

Computer Programming Computer Programming Introduction Marius Minea marius@cs.upt.ro http://cs.upt.ro/ marius/curs/cp/ 26 September 2017 Course goals Learn programming fundamentals no prior knowledge needed for those who know,

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

Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

More information

Definition MATH Benjamin V.C. Collins, James A. Swenson MATH 2730

Definition MATH Benjamin V.C. Collins, James A. Swenson MATH 2730 MATH 2730 Benjamin V.C. Collins James A. Swenson s and undefined terms The importance of definition s matter! may be more important in Discrete Math than in any math course that you have had previously.

More information

Defining Functions 1 / 21

Defining Functions 1 / 21 Defining Functions 1 / 21 Outline 1 Using and Defining Functions 2 Implementing Mathematical Functions 3 Using Functions to Organize Code 4 Passing Arguments and Returning Values 5 Filter, Lambda, Map,

More information

Arithmetic expressions can be typed into Maple using the regular operators:

Arithmetic expressions can be typed into Maple using the regular operators: Basic arithmetic Arithmetic expressions can be typed into Maple using the regular operators: (type "3 + 4" and then press "[Enter]" to start the evaluation of the expression) 7 (1.1) 5 (1.2) 21 (1.3) (type

More information

Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

More information

Introduction to Functional Programming (Python) John R. Woodward

Introduction to Functional Programming (Python) John R. Woodward Introduction to Functional Programming (Python) John R. Woodward Functional Programming 1. Programming paradigm? Object oriented, imperative 2. Immutable state (referential transparency) 3. Higher order

More information

Shippensburg Math & Computer Day 2013 Individual Math Contest Solutions

Shippensburg Math & Computer Day 2013 Individual Math Contest Solutions Shippensburg Math & Computer Day 2013 Individual Math Contest Solutions 1. Row n of Pascal s Triangle lists all the coefficients of the expansion of (1 + x) n. What is the smallest value of n for which

More information

More About Factoring Trinomials

More About Factoring Trinomials Section 6.3 More About Factoring Trinomials 239 83. x 2 17x 70 x 7 x 10 Width of rectangle: Length of rectangle: x 7 x 10 Width of shaded region: 7 Length of shaded region: x 10 x 10 Area of shaded region:

More information

Review of the Lectures 21-26, 30-32

Review of the Lectures 21-26, 30-32 Review of the Lectures 21-26, 30-32 1 The Final Exam Monday 11 December, BSB 337, from 8AM to 10AM 2 Examples of Questions recursion and memoization enumeration trees, binary search trees, Huffman codes

More information

Outline. measuring complexity: big-oh complexity classes counting flops: floating-point operations

Outline. measuring complexity: big-oh complexity classes counting flops: floating-point operations Outline 1 Complexity and Cost measuring complexity: big-oh complexity classes counting flops: floating-point operations 2 Cost of Algorithms timing Python programs the unix command time try-except costs

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

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

Statistics Case Study 2000 M. J. Clancy and M. C. Linn Statistics Case Study 2000 M. J. Clancy and M. C. Linn Problem Write and test functions to compute the following statistics for a nonempty list of numeric values: The mean, or average value, is computed

More information

Visual Basic for Applications

Visual Basic for Applications Visual Basic for Applications Programming Damiano SOMENZI School of Economics and Management Advanced Computer Skills damiano.somenzi@unibz.it Week 1 Outline 1 Visual Basic for Applications Programming

More information

Variable and Data Type 2

Variable and Data Type 2 The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 3 Variable and Data Type 2 Eng. Ibraheem Lubbad March 2, 2017 Python Lists: Lists

More information

The counting numbers or natural numbers are the same as the whole numbers, except they do not include zero.,

The counting numbers or natural numbers are the same as the whole numbers, except they do not include zero., Factors, Divisibility, and Exponential Notation Terminology The whole numbers start with zero and continue infinitely., The counting numbers or natural numbers are the same as the whole numbers, except

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

Functional Programming in Haskell Part I : Basics

Functional Programming in Haskell Part I : Basics Functional Programming in Haskell Part I : Basics Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/ madhavan Madras Christian

More information

Outline. elements and behavior executing programs. developing programs use as a calculator converting strings to numbers

Outline. elements and behavior executing programs. developing programs use as a calculator converting strings to numbers Outline 1 The von Neumann Machine elements and behavior executing programs 2 Python Programming developing programs use as a calculator converting strings to numbers 3 Summary + Assignments MCS 260 Lecture

More information

Lecture Notes, CSE 232, Fall 2014 Semester

Lecture Notes, CSE 232, Fall 2014 Semester Lecture Notes, CSE 232, Fall 2014 Semester Dr. Brett Olsen Week 11 - Number Theory Number theory is the study of the integers. The most basic concept in number theory is divisibility. We say that b divides

More information

11.3 Function Prototypes

11.3 Function Prototypes 11.3 Function Prototypes A Function Prototype contains the function s return type, name and parameter list Writing the function prototype is declaring the function. float square (float x); In a function

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

CSC Design and Analysis of Algorithms. Lecture 8. Transform and Conquer II Algorithm Design Technique. Transform and Conquer

CSC Design and Analysis of Algorithms. Lecture 8. Transform and Conquer II Algorithm Design Technique. Transform and Conquer CSC 301- Design and Analysis of Algorithms Lecture Transform and Conquer II Algorithm Design Technique Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more

More information

Test #2 October 8, 2015

Test #2 October 8, 2015 CPSC 1040 Name: Test #2 October 8, 2015 Closed notes, closed laptop, calculators OK. Please use a pencil. 100 points, 5 point bonus. Maximum score 105. Weight of each section in parentheses. If you need

More information

Expressions and Variables

Expressions and Variables Expressions and Variables Expressions print(expression) An expression is evaluated to give a value. For example: 2 + 9-6 Evaluates to: 5 Data Types Integers 1, 2, 3, 42, 100, -5 Floating points 2.5, 7.0,

More information

Python Programming: Lecture 3 Functions

Python Programming: Lecture 3 Functions Python Programming: Lecture 3 Functions Lili Dworkin University of Pennsylvania Last Week s Quiz In one line, write code that will turn the list [9, 9, 9] into the string 90909. Last Week s Quiz In one

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

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

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221 1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221 Functions Recall that an algorithm is a feasible solution to the specific problem. 1 A function is a piece of computer code that accepts

More information

EP578 Computing for Physicists

EP578 Computing for Physicists EP578 Computing for Physicists Topic 3 Selection & Loops Department of Engineering Physics University of Gaziantep Course web page wwwgantepedutr/~bingul/ep578 Oct 2011 Sayfa 1 1 Introduction This lecture

More information

CS227-Scientific Computing. Lecture 3-MATLAB Programming

CS227-Scientific Computing. Lecture 3-MATLAB Programming CS227-Scientific Computing Lecture 3-MATLAB Programming Contents of this lecture Relational operators The MATLAB while Function M-files vs script M-files The MATLAB for Logical Operators The MATLAB if

More information

Our Strategy for Learning Fortran 90

Our Strategy for Learning Fortran 90 Our Strategy for Learning Fortran 90 We want to consider some computational problems which build in complexity. evaluating an integral solving nonlinear equations vector/matrix operations fitting data

More information

Counting shapes 1.4.6

Counting shapes 1.4.6 GRADE R_TERM 1 WEEK TOPIC CONTENT CAMI KEYSTROKE CAMI Program Count in ones 1.1.1.1; 1.1.1.2; 1.1.1.3 1.1.1.4 Cami Math Count pictures 1.1.3.1; 1.1.3.2; 1 & 2 Counting 1.1.3.3; 1.1.3.4; Counting in units

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

Built-in Types of Data

Built-in Types of Data Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),

More information

Introduction to Python

Introduction to Python Introduction to Python CB2-101 Introduction to Scientific Computing November 11 th, 2014 Emidio Capriotti http://biofold.org/emidio Division of Informatics Department of Pathology Python Python high-level

More information

PART 1 PROGRAMMING WITH MATHLAB

PART 1 PROGRAMMING WITH MATHLAB PART 1 PROGRAMMING WITH MATHLAB Presenter: Dr. Zalilah Sharer 2018 School of Chemical and Energy Engineering Universiti Teknologi Malaysia 23 September 2018 Programming with MATHLAB MATLAB Environment

More information

Solve the matrix equation AX B for X by using A.(1-3) Use the Inverse Matrix Calculator Link to check your work

Solve the matrix equation AX B for X by using A.(1-3) Use the Inverse Matrix Calculator Link to check your work Name: Math 1324 Activity 9(4.6)(Due by Oct. 20) Dear Instructor or Tutor, These problems are designed to let my students show me what they have learned and what they are capable of doing on their own.

More information

COP 4516: Math for Programming Contest Notes

COP 4516: Math for Programming Contest Notes COP 4516: Math for Programming Contest Notes Euclid's Algorithm Euclid's Algorithm is the efficient way to determine the greatest common divisor between two integers. Given two positive integers a and

More information

Lecture 2: List algorithms using recursion and list comprehensions

Lecture 2: List algorithms using recursion and list comprehensions Lecture 2: List algorithms using recursion and list comprehensions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 12, 2017 Expressions, patterns

More information

Introduction to Engineering gii

Introduction to Engineering gii 25.108 Introduction to Engineering gii Dr. Jay Weitzen Lecture Notes I: Introduction to Matlab from Gilat Book MATLAB - Lecture # 1 Starting with MATLAB / Chapter 1 Topics Covered: 1. Introduction. 2.

More information