Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Functions
the most important tool for structuring programs
allows modularity
basic definition: def function_name(args): plus indented code block
when function is called, go to the function, with the arguments, run code until you
hit return() (return None
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a statement that extracts a column named stuff from a pandas DataFrame called df and assigns it to a variable this.
w v 1 of 1: 20170324 14:06:23  R
1 this=df["stuff"]
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Given a variable 5 that is associated with the empty string, write some statements that use a
while loop to associate s with a string consisting of exactly 777 asterisks (*) .
suamrr J 11 of 11: 20170119 20:28:23  R
1 n = 777
2 x = 0
3 while x < n:
4
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Assume that a is a 2dimensional numpy array with shape (n,n). Write a statement to construct an array of shape (n1,n1) consisting of all but the rst row
and and all but the rst column of a.
SUBMIT ~/ 6 of 6: 20170303 11:11:16 l
1 a[1:,1:]
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a statement that assigns the standard deviations of each row of a numpy array called a to a variable called a_stddevs. You can assume that numpy has
already been imported as np.
SUBMIT VI 1 of 1: 20170315 10:26:00  R
1 a_stddevs=np . std ( a, ax
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a statement (or statements) that assigns the second and third rows (i.e. the rows with indexes 1 and 2) of a 2dimensional numpy array called a to a
variable called c.
SUBMIT J 2 of 2: 20170310 11:05:41  R 3
l c=a[l:3]
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
An arithmetic progression is a sequence of numbers in which the distance (or difference)
between any two successive numbers if the same. This in the sequence 1, 3, 5, 7, ., the
distance is 2 while in the sequence 6, 12, 18, 24, ., the distance is 6.
Given
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a statement that nds the positions of the minimum element in each column of a 2dlmensional numpy array called a and assigns the resulting vector to a
variable called min_vals. (You can do this with a for loop, but you can also do it in a single stat
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write some Python code that creates an array of 100 uniformly distributed (pseudo) random numbers and assigns them to a variable called r. You can assume
that import numpy.random as npr has already been run.
SUBMIT v/ 1 of 1: 20170315 10:26:16  F
1 r=n
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a statement that constructs a 1dimensional numpy array of length 100, lled with zeros and assigns it to a variable r. (You can assume numpy has
already been imported as np.)
SUBMIT RESET I 11 of 11: 20170303 11:15:33 
1 import numpy as up
2 r=np.
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a for loop that prints in ascending order all the positive integers less than 200 that are
divisible by both 2 and 3, separated by spaces.
SUBMIT 31 of 31: Thu Jan 19 2017 19:51:05 GMT0500 (EST)
1 for i in range(0,200):
2 if(i%2=0) and (i%3=0):
3
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a statement that assigns the mean ofa numpy array called a to a variable called In. You can assume that numpy has already been imported as np.
SUBMIT I 2 of 2: 20170310 11:06:25  l
1 m=a.mean()
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
In this exercise, use the following variables : i,lo, hi, and result. Assume that lo and hi each are
associated with an int and that result refers to 0.
Write a while loop that adds the integers from In up through hi (inclusive), and associates the
sum wi
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a statement that extracts the rst 10 rows of a pandas DataFrame called df and assigns the result to a variable called beginning
SUBMIT v/ 1 of 1: 20170324 14:06:41  R
l beginning=df[0:10]
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a statement that extracts rows 2 to 5 and columns 3 to 6 of a DataFrame called df and assigns the result to a variable called chunk
SUBMIT J 1 of 1: 20170324 14:07:03  R 9
l chunk=df.iloc[2:6,3:7]
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Write a for loop that prints the odd integers 11 through 121 inclusive, each value on a separate
line.
SUBMT ll 1 of 1: 20170119 19:15:53  R
1 for i in range(11, 122, 2):
2 print(i)
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Instructor: Ben Bolker
o
o
http:/www.math.mcmaster.ca/bolker
o
[email protected]: please include 1mp3 in Subject:
HH 314 (sometimes LSB 336); office hours TBA
TA: Jake Szamosi
o
[email protected]: please allow one full business day for response
Grad
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Basic setup
create a figure: fig=plt.figure()
can include figure size figsize=(w,h), background/edge color, resolution (dpi=dots
per inch)
add a subplot (or axes): ax = fig.add_subplot(1,1,1) (rows,columns,which plot)
now can show or save the figure: fig.
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Installation
If youre lucky (but probably not), you can install numpy in the usual way
open PyCharm
go to Preferences/Project: untitled/Project Interpreter
if you dont see numpy in the list of available modules, click on the + in the lower
left corner of
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Corrections
Get the shape of an array via a.shape, not a.shape() (shape is an attribute, not
a method, of an array)
one correct way to check whether an index fits into a list/tuple/string etc. is
def index_ok(i,x):
n = len(x)
return(n <= i < n)
numpy arr
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Errors
Types of errors
syntax errors vs. logic errors
failure modes:
o
obvious failure
Python crashes
machine crashes
o
program stops with an error partway through: bad mandelbrot #0
program never stops (infinite loop)
wrong answer
always
occasionally
Nex
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Conditionals and flow control
Conditionals: Do something if something else is true
Flow control: Go to different places in the code: especially, repeat calculations
Everything we need for interesting programs (the rest is commentary)
Technically we can co
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Basics
need to define symbols first
from sympy import *
# not usually recommended but OK here
x, y = symbols('x','y') # names don't *have* to match but should usually
# or
x = Symbol('x')
print(x)
print(y)
print(x+x+x) # surprise!
# x
# y
# 3*x
then we ca
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
import numpy.random as npr
from project_answers import *
# YAHTZEE
# test that choice() and randint() give same results
npr.seed(1001)
sides=6
p1 = tuple(npr.choice(range(1,sides+1),size=5)
npr.seed(1001)
p2 = tuple(npr.randint(1,sides+1,size=5)
assert(p1
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Logistics
Homework #4 is due at midnight (i.e. 11:59:59 PM) on Weds February 11.
You must submit your homework to the Dropbox on Avenue to Learn as a single text
(.py) file containing two function definitions (int_to_roman and logist_map, as specified
bel
Introduction to Mathematical and Scientific Programming
MATH 1MP3

Winter 2015
Tuples
simple; nonmutable version of lists
faster, safer
can be expressed as x, y, z (or (x,y,z), probably clearer)
empty tuple: ()
tuple with one element: (x,)
can do many of the same things as with lists
x = (1,4,"a",3)
print(x[1]) # indexing
print(x[2