MATH0011: Mathematical Methods II
Code we wrote during lecture 2
python
# Code that asks for your name then says hello to youname = input("What is your name? ")
print("Hello "+name)
# The following attempt doesn't work because of a TypeError
c = input("Enter a temperature in Celsius: ")
print("In Fahrenheit, this is ",9*c/5+32)
# Every variable has a type
a = 1
print(type(a))
b = 1.0
print(type(b))
c = 1+0j
print(type(c))
d = "1"
print(type(d))
e = True
print(type(e))
# * and + do different things for different types
print(10*2)
print("10"*2)
print(10+2)
print("10"+"2")
print("10"+2)
# You can convert between types using int( ), float( ), str( ), complex( ), bool( )
a = "10"
a = int(a)
print(a*2)
# This is a working version of our attempted code above after fixing the TypeError
c = float(input("Enter a temperature in Celsius: "))
print("In Fahrenheit, this is ",9*c/5+32)
## Lists
a = [4,10,3,7,0,-10]
print(a)
print(a[0])
print(a[1])
print(a[2])
print(a[-1])
print(a[-2])
# Changing the value of an item in a list
print(a)
a[1] = 3
print(a)
# Slices
print(a[0:2])
print(a[:2])
print(a[3:5])
print(a[3:])
print(a[1:5:2])
print(a[::2])
print(a[::-1])
# Slicing also works on strings
words = "This is a string!"
print(words[5])
print(words[7:])
print(words[::2])
print(words[::-1])
# You can use append to add to the end of a list
a = [4,10,3,7,0,-10]
print(a)
a.append(7)
print(a)
# You can use + to concatenate two lists together
print(a + [2,3,4,5,6])
a += [3,6,7]
# Lists can contain a mix of types or be empty
b = [True, "Hello", 4, 3+2j, 5, [4, 5]]
c = []
# You can use for to iterate through a list
a = [4,10,3,7,0,-10]
for i in a:
print(i**2)
# Example: Make a list containing the square numbers below 1000
squares = []
i = 0
while i**2 < 1000:
squares.append(i**2)
i += 1
print(squares)
# Example: Print out all the square numbers up to 1000 whose final digit is 4
for s in squares:
if s%10 == 4:
print(s)
# Some useful functions you can apply to lists
a = [4,10,3,7,0,-10,7,7,7,7]
print(a)
print(max(a))
print(min(a))
print(sum(a))
print(len(a))
# Sorts the list into order
a.sort()
print(a)
# Counts the number of 7s in the list
print(a.count(7))
# Example: Print out the numbers whose squares are less
# than 1000 and have final digit 4
squares = []
i = 0
while i**2 < 1000:
squares.append(i**2)
i += 1
for i,s in enumerate(squares):
if s%10 == 4:
print(i)
# enumerate make the first variable go 0,1,2,3,...
# and the second variable go through the items in the list
# Example: Generating a list of prime numbers up to 1000
# First version
primes = []
for n in range(2,1000):
a = True
for i in range(2,n):
if n%i == 0:
a = False
if a:
primes.append(n)
# Better version
primes = []
for n in range(2,1000):
a = True
for i in primes:
if n%i == 0:
a = False
break
if i**2 > n:
break
if a:
primes.append(n)
print(primes)
# Example: Make a list containing Fibonacci numbers up to 1000
fib = [1,1]
while fib[-1] < 1000:
fib.append(fib[-1]+fib[-2])
print(fib)
## Dictionaries
a = {"cat":5, "dog":3, "fish":0}
print(a)
print(a["cat"])
a["cat"] += 2
print(a["cat"])
a["dog"] = 0
print(a)
# Iterating through dictionaries
for i in a:
print(i)
for i in a.keys():
print(i)
for i in a.values():
print(i)
for i,j in a.items():
print(i, j)
## Tuples
a = (2,3,10)
print(a)
print(a[0])
a[0] = 2
# Tuples with 1 or 0 items looks weird
b = (1,)
c = (,)
# Saving to and loading a list from a file.
# You probably don't need this, but I included it
# in case you want it for the project.
# Save
a = [1,2,3,4]
import json
with open("list.json","w") as f:
json.dump(a, f)
# Load
with open("list.json") as f:
a = json.load(f)
print(a)
## Functions
def f(x):
return x**2
print(f(4))
a = f(5)
print(a)
# Functions can have no inputs.... although this isn't very useful
def a():
print("Hello World")
a()
# Functions can have multiple inputs
def multiply_and_print(a, b):
print(a*b)
multiply_and_print(5,3)
# Example: Function that returns the product of a list
def product(a):
"Returns the product of all the items in a list"
output = 1
for i in a:
output *= i
return output
print(product([2,3,4,5,6,7]))
# If the first line of a function is a string, then it
# can be viewed by calling help on the function
help(product)
# Example: Write a choose function
def factorial(n):
output = 1
for i in range(2,n+1):
output *= i
return output
def choose(n,r):
"Returns n choose r, or n!/r!(n-r)!"
a = factorial(n)
a /= factorial(r)
a /= factorial(n-r)
return a
print(choose(10,5))
# Example: Write a solve function that solves ax^2+bx+c=0
def solve(a, b, c):
"Returns the solution(s( of ax**2+bx+c=0"
root = (b**2-4*a*c)**(1/2)
if b**2-4*a*c == 0:
ans = -b/(2*a)
return ans
else:
ans1 = (-b+root)/(2*a)
ans2 = (-b-root)/(2*a)
return ans1,ans2
# Solve x**2+5x+6=0
print(solve(1,5,6))
# Solve x**2+6x+9=0
print(solve(1,6,9))
# Solve x**2+6x+10=0
print(solve(1,6,10))
# Example: How many times must this function be applied, starting at 2019, to reach 1?
def f(x):
if x%2 == 0:
return x//2
else:
return x+1
n = 2019
count = 0
while n != 1:
n = f(n)
count += 1
print(count)