# Math 1MP3

## Website for Brydon's Math 1MP3 tutorials!

##### Tu: 13:30-14:20 (BSB 249) Th: 10:30-11:20 (BSB 244) Fr: 14:30-15:20 (BSB 244)

With all these tutorial quesitons, don’t worry if you can’t do them all in the 50 minutes (usually less, because I make announcements too). Instead, focus on one or two that you think you mostly understand, and ask me questions until you fully understand. Some of these tutorial questions are really hard!

# Last Week of Class

We will be covering some general course review in tutorial this week. Come with Final Project questions too! On Thursday, April 6 there will be a more focused final exam review session held in BSB 244 at 10:30. All are welcome!.

# Friday, March 24th tutorial is CANCELLED!

Have a nice weekend!

# Tutorial 9

## (Week of Mar23-28, 2017)

Today’s tutorial covers pandas and dataframes. Find the tutorial pdf here.

The solutions are posted sols-tut8.py:

``````import numpy as np
import matplotlib.pyplot as plt

# Question 1

def partial_sum_sin(x,N):
s = np.zeros(len(x))
for i in range(N+1):
s += (-1)**i/np.math.factorial(2*i+1)*x**(2*i+1)
return s

x = np.arange(-30,30,0.1)

plt.plot(x,partial_sum_sin(x, 10),'r')
plt.plot(x,partial_sum_sin(x, 50),'g')
plt.plot(x,partial_sum_sin(x, 100),'b')
plt.plot(x,np.sin(x),'k')

plt.axis([-30,30,-2,2])

plt.show()

def partial_sum_sin_tol(x,tol=10**(-5)):
s = np.zeros(len(x))
i = 0
while max(x)**(2*i+3)/np.math.factorial(2*i+3) > tol:
s += (-1)**i/np.math.factorial(2*i+1)*x**(2*i+1)
i += 1
return s

plt.plot(x,partial_sum_sin_tol(x),'r')
plt.plot(x,np.sin(x),'k')

plt.axis([-30,30,-2,2])

plt.show()

# Question 2

def f(x,mu,sigma):
return 1/np.sqrt(2*sigma**2*np.pi)*np.exp(-(x-mu)**2/(2*sigma**2))

mu = 50
sigma = 8
data = np.random.randn(1000) * sigma + mu

x = np.arange(0,100,0.1)

plt.hist(data,25,normed=1)

plt.plot(x,f(x,mu,sigma))
plt.axis((0,100,0,0.075))

plt.show()

``````

# Tutorial 8

## (Week of Mar16-21, 2017)

This tutorial covers matplotilb and making plots with numpy. Find the tutorial pdf here.

The solutions are posted sols-tut8.py:

``````import numpy as np
import matplotlib.pyplot as plt

# Question 1

def partial_sum_sin(x,N):
s = np.zeros(len(x))
for i in range(N+1):
s += (-1)**i/np.math.factorial(2*i+1)*x**(2*i+1)
return s

x = np.arange(-30,30,0.1)

plt.plot(x,partial_sum_sin(x, 10),'r')
plt.plot(x,partial_sum_sin(x, 50),'g')
plt.plot(x,partial_sum_sin(x, 100),'b')
plt.plot(x,np.sin(x),'k')

plt.axis([-30,30,-2,2])

plt.show()

def partial_sum_sin_tol(x,tol=10**(-5)):
s = np.zeros(len(x))
i = 0
while max(x)**(2*i+3)/np.math.factorial(2*i+3) > tol:
s += (-1)**i/np.math.factorial(2*i+1)*x**(2*i+1)
i += 1
return s

plt.plot(x,partial_sum_sin_tol(x),'r')
plt.plot(x,np.sin(x),'k')

plt.axis([-30,30,-2,2])

plt.show()

# Question 2

def f(x,mu,sigma):
return 1/np.sqrt(2*sigma**2*np.pi)*np.exp(-(x-mu)**2/(2*sigma**2))

mu = 50
sigma = 8
data = np.random.randn(1000) * sigma + mu

x = np.arange(0,100,0.1)

plt.hist(data,25,normed=1)

plt.plot(x,f(x,mu,sigma))
plt.axis((0,100,0,0.075))

plt.show()

``````

# Tutorial 7

## (Week of Mar6-10, 2017)

The following tutorial goes over the basics of the numpy library, covering arrays in depth and all the little things you’ll want to do with them. Try running the code presented (with print statements as necessary) and answering all the little questions sprinkled throughout the file.

The goal of this tutorial is to get you acquainted with all the many little tricks in numpy for manipulating arrays (beyond just base-python methods) and all the special functions for creating special arrays. That way you’ve at least once seen how to do it, so you have a resource to flip back to.

At the end of the tutorial is one question (similar in size to previous tutorials) to test these concepts.

Find the tutorial pdf here you will also need this text file.

The solutions are posted sols-tut7.py:

``````import numpy as np

def random_matrix_fun(n):
B = 10 * np.random.random((n,n+1)) - 5

A = B[:,:n]
x = B[:,-1]

b = np.matmul(A,x)

print(b)

w,X = np.linalg.eig(A)

allRight = True
for i in range(n):
if not np.allclose(w[i]*X[:,i], np.matmul(A,X[:,i])):
print("At least one eigenvalue is wrong!")
allRight = False
break

if allRight:
print("All the eigenvalues are correct!")

return [A,b,w]

print(random_matrix_fun(3))

``````

# Tutorial 6

## (Week of Feb9-14, 2017)

For this tutorial, we will be working on dictionaries! Along the way we’ll do some loops, file I/O, if statements, and even some stuff with lists! Find the tutorial file here.

The solutions are posted sols-tut6.py:

``````# Q1a

""" Concatenates two dictionaries """
d = dict1.copy()
for key in dict2:
d[key] = dict2[key]
return d

# Q1b

""" Concatenates two dictionaries, if they have the same keys then values are added """
d = dict1.copy()
for key in dict2:
if key in dict1:
d[key] += dict2[key]
else:
d[key] = dict2[key]
return d

# Q2a

def no_spaces(d):
output = d.copy()
for key in d:
if " " in key:
old_value = output.pop(key)
new_key = key.replace(" ","_")
output[new_key] = old_value
return output

# Q2b

def no_spaces(d):
output = d.copy()
for key in d:
if " " in key:
old_value = output.pop(key)
new_key = key.replace(" ","_")
if new_key in d:
output[new_key] += old_value
return output

# Q3a

def string_to_dict(s):
d = {}
for letter in s:
if letter in d:
d[letter] += 1
else:
d[letter] = 1
return d

# Q3cd

f = open("2600-0.txt")
f.close()

wap_dict = string_to_dict(wap_content)

# Q3e
for letter in "abcdefghijklmnopqrstuvwxyz":
print(wap_dict[letter])

# Q4a
def dictionary_max(d):
biggest = None
for key in d:
if biggest is None:
biggest = d[key]
break
elif d[key] > biggest:
biggest = d[key]
break
return biggest

# Q4b
def dictionary_max(d):
biggest_val = None
biggest_key = None
for key in d:
if biggest_val is None or d[key] > biggest_val:
biggest_val = d[key]
biggest_key = key
break
return biggest_key

# Q4c

def dictionary_max(d, n=1):
biggest_val = [None]*n
biggest_key = [None]*n
for key in d:
for i in range(n):
if biggest_val[i] is None or d[key] > biggest_val[i]:
biggest_val = biggest_val[:i] + [d[key]] + biggest_val[i:-1]
biggest_key = biggest_key[:i] + [key] + biggest_key[i:-1]
break
return biggest_key

print(dictionary_max(wap_dict, 5))

``````

# Tutorial 5

## (Week of Feb 2-7, 2017)

For this week’s tutorial we look at some basic file i/o, some more function stuff, the dangers of floating point problems, and just some general python tricks. Find the tutorial pdf here. Question 1 also requires use of lipsum.txt.

The solutions are posted sols-tut5.py:

``````import math

# Question 1a
f = open("lipsum.txt")
f.close()
print(text)

# Question 1b
f = open("lipsum.txt")
f.close()
return text.split("\n")

# Question 2a
sum = 0
for i in range(10):
sum += 0.1
if sum == 0.3:
break
print(sum)
print("We expected 0.3, didn't get that at all")

# Question 2b
number = 9.3

while number % 0.5 != 0:
number -= 0.1

print(number)
print("We expected 9.0, not even CLOSE")

# Question 2c
sum = 0
for i in range(10):
sum += 0.1
if abs(sum - 0.3) < 1e-6:
break
print(sum)
print("We expected 0.3, got close enough!")

# Question 3
No real roots: returns None
One real root: returns [root]
otherwise returns a sorted list of the roots"""

discr = b**2-4*a*c
if discr < 0:
return None
if discr == 0:
return [-b/(2*a)]
retlist = [(-b+math.sqrt(discr))/(2*a),
(-b-math.sqrt(discr))/(2*a)]
retlist.sort()
return retlist

# Question 4
def all_even(minimum, maximum):
"""Returns a list of integers between min and max (inclusive) whose digits (base 10) are all even"""
values = []
for i in range(minimum, maximum+1):
s = str(i)
alleven = True

for digit in s:
if int(digit) % 2 != 0:
alleven = False
break

if alleven:
values.append(s)

return values

print(all_even(100, 300))

``````

# Tutorial 4

## (Week of Jan 26-31, 2017)

For this week’s tutorial we will be focusing on python exercises dealing with functions and recursion. Find the tutorial pdf here.

The solutions are posted sols-tut4.py:

``````def number_to_day(n):
"""
Takes a number, returns a string representing day of the week
:param n:
:return Day of the week as a string:
"""
if n == 1:
return "Sunday"
elif n == 2:
return "Monday"
elif n == 3:
return "Tuesday"
elif n == 4:
return "Wednesday"
elif n == 5:
return "Thursday"
elif n == 6:
return "Friday"
elif n == 7:
return "Saturday"

def my_max(in_list):
"""
Returns the maximum of the list
:param in_list:
:return the maximal element in the in_list:
"""
biggest = in_list
for l in in_list:
if l > biggest:
biggest = l
return biggest

def case_count(in_string):
"""
Counts the number of lower and upper case letters in a string
:param in_string:
:return list of two numbers, first number how many lowercase letters, second number how many uppercase letters:
"""
uppercase_count = 0
lowercase_count = 0

for letter in in_string:
if letter != " ":
if letter == letter.upper():
uppercase_count += 1
else:
lowercase_count += 1

return [lowercase_count, uppercase_count]

def make_unique(in_list):
"""
Removes duplicates from a list, preserving ordering of the first appearance of an element
:param in_list:
:return a set of unique elements of in_list:
"""
new_list = []
for l in in_list:
if l not in new_list:
new_list.append(l)
return new_list

def is_prime(n):
"""
Tests if a number n is prime
:param n:
:return True/False:
"""
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True

def only_even(in_list):
"""
Creates a new list of even elements of the input list
:param in_list:
:return a new list of even elements of list:
"""
new_list = []
for l in in_list:
if l % 2 == 0:
new_list.append(l)
return new_list

def make_primes(n):
"""
Makes a list of primes less than n
:param n:
:return a list of all primes less than n:
"""
out_list = []
for i in range(2, n):
if is_prime(i):
out_list.append(i)
return out_list

if __name__ == "__main__":
# Run all the test cases!
# This should all return True, otherwise something's wrong!
print("Question 1")
print(number_to_day(1) == "Sunday")

print("Question 2")
print(my_max([1, 2, 3]) == 3)
print(my_max([1, 0, 100, -2]) == 100)
print(my_max([-1, -2, -3]) == -1)

print("Question 3")
print(case_count("The Quick Brown Fox") == [12, 4])

print("Question 4")
print(make_unique([1, 2, 3, 3, 4, 4, 6, 5, 5, 5, 7, 5]) == [1, 2, 3, 4, 6, 5, 7])

print("Question 5")
print(is_prime(23))
print(is_prime(161) is False)
print(is_prime(211))

print("Question 6")
print(only_even([1, 2, 3, 4, -1, -2, 9, 27, 32, 2]) == [2, 4, -2, 32, 2])

print("Question 7")
print(make_primes(10) == [2, 3, 5, 7])
print(make_primes(50) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47])

``````

# Tutorial 3

## (Week of Jan 19-24, 2017)

For this week’s tutorial we will be focusing on python exerises dealing with loops and lists – and often, how the two interact.

The tutorial pdf file can be found here, as with last week some questions are much harder than others (Question 5, for instance).

The solutions are posted sols-tut3.py:

``````# Lab 2 Q8
for i in range(1,11):
print(i)

output = 0
for i in range(1,101):
output += i
print(output)

result = 1
for i in range(1,9):
result *= i

print(result)

# Lab 2 Q 9
fib = [1, 1]

for i in range(20):
fib.append(fib[-1]+fib[-2])

print(fib)

# Lab 3 Q1
for i in range(1,101):
if i % 3 == 0 and i % 5 == 0:
print("fizzbuzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print(i)

# Lab 3 Q2 -- one option
for i in range(1,6):
line = ""
for j in range(i):
line += str(i)
print(line)

# Alternative

for i in range(1,6):
for j in range(i):
print(i,end="")
print()

# Lab 3 Q3
lista = ["a","b","c","d","e","f","g","h","g","f"]

print(lista.index("b"))

letter = "f"

for index in range(len(lista)):
if lista[index] == letter:
print(index)
break

for index in range(len(lista)):
if lista[index] == letter:
print(index)

# Lab 3 Q4

vector = [10,14,16,20]

vector.sort()

length = len(vector)

if length % 2 == 0:
middle1 = int(length/2)
middle2 = middle1 - 1
middlenumber = (vector[middle1]+vector[middle2])/2
print(middlenumber)
else:
middle = int(length/2)
print(vector[middle])

# Lab 3 Q5

population = 120
for i in range(100):
population = 6*population/(2+population)

print(population)

# Part b

population = 120
years = 0
while abs(population-4)>=0.01:
years += 1
population = 6*population/(2+population)
print(years)

``````

# Tutorial 2

## (Week of Jan 12-17, 2017)

For this week’s tutorial we will be working through python exercises dealing with assignment, strings, lists, and loops.

These exercises are varying difficulty – for instance 1,2, and 3 are /relatively/ easy. While 7 and 9 are hard.

The tutorial pdf file can be found here.

The solutions are posted sols-tut2.py:

``````## Question 1
height = 4
length = 6
print(height*length)

## Question 2
base = 6
height = 3
print(base*height/2)

## Question 3
first_name = "brydon"
last_name = "eastman"

# Part a
print(first_name+" "+last_name)

# Part f
print(first_name.capitalize()+" "+last_name.capitalize())

## Question 4
birth_country = "America"

# One way

temp = birth_country
birth_country = home_country
home_country = temp

# Alterative!
birth_country, home_country = home_country, birth_country

## Question 5

vector = [1,2,3,4,5,7,8,10]
mean = sum(vector)/len(vector)
print(mean)

## Question 6
alpha = ['a','b','c','d']
beta = alpha.copy() # Note, since lists are immutable, you need the copy!
alpha.reverse() # This changes alpha /in place/ to ['d','c','b','a']
beta = beta + alpha # or beta += alpha, whatever you prefer !
print(beta)
# Note the similarities between this and question 4!

## Question 7

# Part a
print(act1scene1.count("Romeo"))

# Part b
print(act1scene1.lower().count("quarrel"))

# Part c
index1 = act1scene1.find("Romeo")
index2 = act1scene1.find("Romeo",index1+1)

inbetween_text = act1scene1[index1++len("Romeo"):index2]
print(inbetween_text)

## Question 8
# Part a
for i in range(1,11):
print(i)

# Part b
sum = 0
for i in range(1,11):
sum += i
print(sum)

# Part c
result = 1
for i in range(1,9):
result *= i
print(result)

## Question 9
fib = [1,1]
for i in range(20):
fib.append(fib[-1]+fib[-2])
print(fib)

## Question 10
# Part a
# Prints 10,9,8,7,6
# Part b
# Prints ['ab','cd','AB','CD']

``````

# Tutorial 1

## (Week of Jan 5-11, 2017)

For this week’s tutorial we will be installing Anaconda and PyCharm and that’s it! Here’s the slides for the week.

For Anaconda make sure you select the Python 3.5 installer! If you’re on Mac choose the graphical installer, unless you like bash! Most computers will be 64 bit. If you want to check

• In Mac or Linux open a Terminal and type
``````uname -p
``````

If the output is i386 then you are a 32 bit computer, if it is x86_64 then you are a 64 bit computer

• In Windows open a Comand Line and type
``````wmic os get osarchitecture
``````

For PyCharm make sure you install the community version and everytime you make a new project make sure the interpreter is pointed towards your anaconda installation!