Python for A-Level Mathematics and Beyond¶

CHAPTER 1: Solutions to Python Exercises¶

Exercises 1.5.1 Calculator Commands¶

1.5.1.1 Use Python to evaluate:

(a) $2-(3+6)$; (b) $2(5-8(3+6))$; (c) 2(2-2(3-6+5(4-7))); (d) $\frac{2(5-4(3+8))}{3(4-(3-5))}$; (e) $\frac{2 \times 4^5}{81-5!}$.

In [1]:
2 - (3 + 6)
Out[1]:
-7
In [2]:
2  * (5 - 8 * (3 + 6))
Out[2]:
-134
In [3]:
2 * (2 - 2 * (3 - 6 + 5 * (4 - 7)))
Out[3]:
76
In [4]:
(2 * (5 - 4 * (3 + 8))) / (3 * (4 - (3 - 5)))
Out[4]:
-4.333333333333333
In [5]:
from math import *
(2 * 4**5) / (81 - factorial(5))
Out[5]:
-52.51282051282051

1.5.1.2 Use Python to evaluate:

(a) $\sqrt{4+6^5+5!}$; (b) $\cos(0.8)$; (c) $\arctan(-0.4)$; (d) $\ln(87.95)$; (e) $\log_{10}(725.345)$.

In [6]:
from sympy import *
sqrt(4 + 6**5 + factorial(5))
Out[6]:
$\displaystyle 10 \sqrt{79}$
In [7]:
cos(0.8)
Out[7]:
$\displaystyle 0.696706709347165$
In [8]:
atan(-0.4)
Out[8]:
$\displaystyle -0.380506377112365$
In [9]:
log(87.95)
Out[9]:
$\displaystyle 4.47676847118357$
In [10]:
log10(725.345)
Out[10]:
2.8605446216854427

1.5.1.3 Use Python to evaluate symbolically:

(a) $\frac{1}{3} \times \frac{1}{4}-\frac{1}{5}$; (b) $\left(\frac{1}{3} - \frac{2}{5} \right)^3$; (c) $\frac{1}{7} \times \frac{4}{23} \div \frac{37}{125}$; (d) $\left(\sqrt{2}-3 \right)^4$; (e) $\frac{1}{\sqrt{2}+3}$.

In [11]:
from fractions import Fraction
Fraction(1, 3) * Fraction(1, 4) - Fraction(1, 5)
Out[11]:
Fraction(-7, 60)
In [12]:
(Fraction(1, 3) - Fraction(2, 5))**3
Out[12]:
Fraction(-1, 3375)
In [13]:
Fraction(1, 7) * Fraction(4, 23) / Fraction(37, 125)
Out[13]:
Fraction(500, 5957)
In [14]:
from sympy import expand
expand((sqrt(2) - 3)**4)
Out[14]:
$\displaystyle 193 - 132 \sqrt{2}$
In [15]:
from sympy import simplify
simplify((1 / (sqrt(2) + 3)))
Out[15]:
$\displaystyle \frac{3}{7} - \frac{\sqrt{2}}{7}$

1.5.1.4 Use Python to evaluate:

(a) $\cos^2(0.9)$; (b) $\ln(8)-\log_{10}(56)$; (c) $12!$; (d) $5186 \mod 8$; (e) floor$(5\pi-2e)$.

In [16]:
(cos(0.9))**2
Out[16]:
$\displaystyle 0.386398952653456$
In [17]:
round(log(8) - log10(56),5)
Out[17]:
$\displaystyle 0.33125$
In [18]:
factorial(12)
Out[18]:
$\displaystyle 479001600$
In [19]:
fmod(5186, 8)
Out[19]:
2.0
In [20]:
floor(5 * pi - 2 * exp(1))
Out[20]:
$\displaystyle 10$

Exercises 1.5.2 Symbolic Computation¶

1.5.2.1 Use Python to:

(a) factorize $x^3-y^3$; (b) solve $x^2-7x-30=0$; (c) split $\frac{3x}{(x-1)(x+2)(x-5)}$; (d) simplify $y=\sin^4(x)-2\cos^2(x)\sin^2(x)+\cos^4(x)$; (e) expand $(y+x-3)(x^2-y+4)$.

In [21]:
from sympy import *
x, y = symbols('x y')
factor(x**3 - y**3)
Out[21]:
$\displaystyle \left(x - y\right) \left(x^{2} + x y + y^{2}\right)$
In [22]:
solve(x**2 - 7 * x - 30)
Out[22]:
[-3, 10]
In [23]:
apart(3 * x / ((x - 1) * (x + 2) * (x - 5)))
Out[23]:
$\displaystyle - \frac{2}{7 \left(x + 2\right)} - \frac{1}{4 \left(x - 1\right)} + \frac{15}{28 \left(x - 5\right)}$
In [24]:
trigsimp(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4)
Out[24]:
$\displaystyle \frac{\cos{\left(4 x \right)}}{2} + \frac{1}{2}$
In [25]:
expand((y - x - 3) * (x**2 - y + 4))
Out[25]:
$\displaystyle - x^{3} + x^{2} y - 3 x^{2} + x y - 4 x - y^{2} + 7 y - 12$

1.5.2.2 Determine:

(a) $lim_{n \rightarrow \infty} \left(1+\frac{1}{n} \right)^n$; (b) $\frac{d}{dx}\left(3x^4-6x^3 \right)$; (c) $\frac{d^3}{dx^3}\left(3x^4-6x^3 \right)$; (d) $\int_{x=0}^1 x^2-2x-3 \, dx$;

(e) the first 10 terms of the Taylor series expansion of $e^x \sin(x)$, about $x=1$.

In [26]:
n = symbols('n')
limit((1 + 1 / n)**n, n, oo)
Out[26]:
$\displaystyle e$
In [27]:
diff(3 * x**4 - 6 * x**3, x)
Out[27]:
$\displaystyle 12 x^{3} - 18 x^{2}$
In [28]:
diff(3 * x**4 - 6 * x**3, x, 3)
Out[28]:
$\displaystyle 36 \left(2 x - 1\right)$
In [29]:
integrate(x**2 - 2 * x - 3, (x, 0, 1))
Out[29]:
$\displaystyle - \frac{11}{3}$
In [30]:
(exp(x) * sin(x)).series(x , 1, 10)
Out[30]:
$\displaystyle e \sin{\left(1 \right)} + \left(x - 1\right) \left(e \cos{\left(1 \right)} + e \sin{\left(1 \right)}\right) + e \left(x - 1\right)^{2} \cos{\left(1 \right)} + \left(x - 1\right)^{3} \left(- \frac{e \sin{\left(1 \right)}}{3} + \frac{e \cos{\left(1 \right)}}{3}\right) - \frac{e \left(x - 1\right)^{4} \sin{\left(1 \right)}}{6} + \left(x - 1\right)^{5} \left(- \frac{e \sin{\left(1 \right)}}{30} - \frac{e \cos{\left(1 \right)}}{30}\right) - \frac{e \left(x - 1\right)^{6} \cos{\left(1 \right)}}{90} + \left(x - 1\right)^{7} \left(- \frac{e \cos{\left(1 \right)}}{630} + \frac{e \sin{\left(1 \right)}}{630}\right) + \frac{e \left(x - 1\right)^{8} \sin{\left(1 \right)}}{2520} + \left(x - 1\right)^{9} \left(\frac{e \cos{\left(1 \right)}}{22680} + \frac{e \sin{\left(1 \right)}}{22680}\right) + O\left(\left(x - 1\right)^{10}; x\rightarrow 1\right)$

1.5.2.3 Use Python to:

(a) sum $\sum_{n=1}^{\infty} \frac{1}{n}$; (b) sum $\sum_{n=1}^{20} (2+3(n-1))$; (c) sum $\sum_{n=1}^{20} 2 \times 3^n$;

(d) solve $2x-y=9, 3x+y=8$; (e) solve $x^2-y=2, x+y=1$.

In [31]:
summation(1 / n, (n, 1, oo))
Out[31]:
$\displaystyle \infty$
In [32]:
summation(2 + 3 * (n - 1), (n, 1, 20))
Out[32]:
$\displaystyle 610$
In [33]:
summation(2 * 3**n, (n, 1, 20))
Out[33]:
$\displaystyle 10460353200$
In [34]:
solve([2 * x - y - 9, 3 * x + y - 8] , [x, y])
Out[34]:
{x: 17/5, y: -11/5}
In [35]:
solve([x**2 - y - 2, x + y - 1] , [x, y])
Out[35]:
[(-1/2 + sqrt(13)/2, 3/2 - sqrt(13)/2), (-sqrt(13)/2 - 1/2, 3/2 + sqrt(13)/2)]

1.5.2.4 Given that:

$A=\begin{equation*} \begin{pmatrix} -1 & 2 & 4 \\ 0 & 3 & 2 \\ 1 & 4 & 6 \end{pmatrix} \end{equation*}$

and

$B=\begin{equation*} \begin{pmatrix} 2 & 3 & 3 \\ 0 & 3 & 0 \\ -6 & 1 & 1 \end{pmatrix} \end{equation*}$,

use Python to evaluate:

(a) $3A-5B$; (b) $A \times B$; (c) the inverse of $A$; (d) the first column of $A \times B$; (e) the transpose of $A \times B$.

In [36]:
A = Matrix([[-1, 2, 4],[0, 3, 2],[1, 4, 6]])
In [37]:
B = Matrix([[2, 3, 3],[0, 3, 0],[-6, 1, 1]])
In [38]:
3 * A - 5 * B
Out[38]:
$\displaystyle \left[\begin{matrix}-13 & -9 & -3\\0 & -6 & 6\\33 & 7 & 13\end{matrix}\right]$
In [39]:
A * B
Out[39]:
$\displaystyle \left[\begin{matrix}-26 & 7 & 1\\-12 & 11 & 2\\-34 & 21 & 9\end{matrix}\right]$
In [40]:
A**(-1)
Out[40]:
$\displaystyle \left[\begin{matrix}- \frac{5}{9} & - \frac{2}{9} & \frac{4}{9}\\- \frac{1}{9} & \frac{5}{9} & - \frac{1}{9}\\\frac{1}{6} & - \frac{1}{3} & \frac{1}{6}\end{matrix}\right]$
In [41]:
((A * B)).col(0)
Out[41]:
$\displaystyle \left[\begin{matrix}-26\\-12\\-34\end{matrix}\right]$
In [42]:
(A * B).T
Out[42]:
$\displaystyle \left[\begin{matrix}-26 & -12 & -34\\7 & 11 & 21\\1 & 2 & 9\end{matrix}\right]$

Exercises 1.5.3 Numerical Python and MatPlotLib¶

1.5.3.1 Use Python to generate the following lists:

(a) a list of integers from 5 to 200;

(b) a list of even integers from -4 to 200;

(c) a list of the form $[3,6,9,...,300]$;

(d) a list of the form $[30,27,24,...,-3]$;

(e) a list of the form $[[1,2,...,100],[101,102,...,200],[201,202,...,300]]$.

In [43]:
list(range(5, 201, 1));  # Semi-colon suppresses output.
In [44]:
list(range(-4, 201, 2));
In [45]:
list(range(3, 301, 3));
In [46]:
list(range(30, -4, -3))
Out[46]:
[30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, -3]
In [47]:
[list(range(1, 101)),list(range(101, 201)),list(range(201, 301))];

1.5.3.2 Given the array of numbers:

2 6 0 6 -5 2 6 0 8 -9

-1 8 7 4 1 -1 9 9 4 1

0 24 8 2 12 0 14 8 1 2

determine:

(a) the sum of each row; (b) the sum of each column; (c) the minimum of each row; (d) the maximum of each column; (e) the cumulative sum for each row.

In [48]:
import numpy as np
A = np.array([[2,6,0,6,-5,2,6,0,8,-9],[-1,8,7,4,1,-1,9,9,4,1],[0,24,8,2,12,0,14,8,1,2]])
In [49]:
A.sum(axis = 1)
Out[49]:
array([16, 41, 71])
In [50]:
A.sum(axis = 0)
Out[50]:
array([ 1, 38, 15, 12,  8,  1, 29, 17, 13, -6])
In [51]:
A.min(axis = 1)
Out[51]:
array([-9, -1,  0])
In [52]:
A.max(axis = 0)
Out[52]:
array([ 2, 24,  8,  6, 12,  2, 14,  9,  8,  2])
In [53]:
A.cumsum(axis = 1)
Out[53]:
array([[ 2,  8,  8, 14,  9, 11, 17, 17, 25, 16],
       [-1,  7, 14, 18, 19, 18, 27, 36, 40, 41],
       [ 0, 24, 32, 34, 46, 46, 60, 68, 69, 71]])

1.5.3.3 Plot the following functions:

(a) $y=x^2-3x-18$; (b) $y=\cos(2x)$; (c) $y=\sin^2(x)$; (d) $y=4x^3-3x^4$; (e) $y=\cosh(x)$.

In [54]:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-7, 10, 100)
y = x**2 - 3 * x - 18
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Parabola')
plt.show()
In [55]:
x = np.linspace(- 2 * np.pi, 2 * np.pi, 100)
y = np.cos(2 * x)
plt.plot(x, y)
plt.xlabel('x', fontsize = 15)
plt.ylabel('y', fontsize = 15)
plt.tick_params(labelsize = 15)
plt.title('$y=\cos(2x)$', fontsize = 15)
plt.show()
In [56]:
x = np.linspace(- 2 * np.pi, 2 * np.pi, 100)
y = np.sin(x)**2
plt.plot(x, y)
plt.xlabel('x', fontsize = 15)
plt.ylabel('y', fontsize = 15)
plt.tick_params(labelsize = 15)
plt.title('$y=\sin^2(x)$', fontsize = 15)
plt.show()
In [57]:
x = np.linspace(-1.2, 1.9, 100)
y = 4 * x**3 - 3 * x**4
plt.plot(x, y)
plt.xlabel('x', fontsize = 15)
plt.ylabel('y', fontsize = 15)
plt.tick_params(labelsize = 15)
plt.title('$y=4x^3-3x^4$', fontsize = 15)
plt.show()
In [58]:
x = np.linspace(-2, 2, 100)
y = np.cosh(x)
plt.plot(x, y)
plt.xlabel('x', fontsize = 15)
plt.ylabel('y', fontsize = 15)
plt.tick_params(labelsize = 15)
plt.title('$y=\cosh(x)$', fontsize = 15)
plt.show()

1.5.3.4 Use the internet to find examples of surface plots in Python. Plot the surface defined by: $z(x,y)=\sin(x)+\cos(y)$.

In [59]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

def fun(x, y):
  return np.sin(x) + np.cos(y)   # The function z(x,y)=sin(x)+cos(y).

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.arange(-4.0, 4.0, 0.1)
y = np.arange(-4.0, 4.0, 0.1)
X, Y = np.meshgrid(x, y)
zs = np.array([fun(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('x',fontsize=12)
ax.set_ylabel('y',fontsize=12)
ax.set_zlabel('z',fontsize=12)
plt.tick_params(labelsize=12)
ax.view_init(30, -70)
plt.show()

CHAPTER 2: Solutions to Python Exercises¶

Exercises 2.7 Programming¶

2.7.1 Write a Python program for each of the following:

(a) A function called sgn that returns $-1$ if $x<0$, $0$ if $x=0$, and $+1$ if $x>0$.

(b) A program called averages that returns the mean, median and mode of a list of real numbers.

(c) A function which returns the sum of the squares of the first n natural numbers. Use the sqr function given in Example 1.

(d) A function called cylinder_volume that inputs two variables, the radius and height of a cylinder, and gives the volume of the cylinder.

(e) A function called cone_mass that inputs three variables, the height, base-radius and density, and returns the mass of the cone.

In [60]:
def sgn(x):
    if x < 0:
        return -1
    elif x == 0:
        return 0
    else:
        return 1

sgn(-35)
Out[60]:
-1
In [61]:
import statistics as stats
data = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
    ele = int(input())
    data.append(ele) # Add the elements. 
print(data)
mean_data = stats.mean(data)
print("mean_data =", mean_data)
median_data = stats.median(data)
print("median_data =", median_data)
mode_data = stats.mode(data)
print("mode_data =", mode_data) 
Enter number of elements : 10
4
6
4
11
7
4
9
13
4
5
[4, 6, 4, 11, 7, 4, 9, 13, 4, 5]
mean_data = 6.7
median_data = 5.5
mode_data = 4
In [62]:
def sqr(x):
    return x**2

def sumsqr(n):
    sum = 0
    i = 1
    while i <= n:
        sum += sqr(i)
        i += 1    # update counter

    print('The sum of the squares is', sum)
    
sumsqr(5)
The sum of the squares is 55
In [63]:
def cylinder_volume(radius, height):
    cv = np.pi * radius**2 * height
    print('The cylinder volume is', cv)
    
cylinder_volume(2, 5)
The cylinder volume is 62.83185307179586
In [64]:
def cone_mass(height, radius, density):
    cm = np.pi * radius**2 * height * density / 3
    print('The mass of the cone is', cm)
    
cone_mass(5, 2, 0.4)
The mass of the cone is 8.377580409572781

2.7.2 Write a Python program that animates the parametric curve defined by $x(t)=\cos(t), y(t)=\sin(nt)$, for $n$ from $0$ to $4$, and $0 \leq t \le 2 \pi$.

In [65]:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(-1.2, 1.2),ylim=(-1.2, 1.2))
line, = ax.plot([],[],lw=2)
plt.xlabel('x')
plt.ylabel('y')
plt.close()

def init():
    line.set_data([],[])
    return line,

# The function to animate. Animate up to sin(4t).
def animate(i):
    t = np.linspace(0, 2 * np.pi, 1000)
    x = np.cos(t)
    y = np.sin(i * t / 25)   # frames = 101.
    line.set_data(x, y)
    return line,

# Note: blit=True means only re-draw the parts that have changed.
# Interval determines the speed of the animation.
anim = animation.FuncAnimation(fig, animate, init_func=init, \
                               frames=101, interval=200, blit=False)

from IPython.display import HTML
HTML(anim.to_jshtml())
Out[65]:

2.7.3

(a) Write a Python program to convert degrees Centigrade to degrees Fahrenheit.

(b) Write a Python program that sums the subset of prime numbers up to some natural number.

In [66]:
def C2F():
    C = float(input('Enter temperature in degrees Centigrade: '))
    F = (C * 9 / 5) + 32
    print('Temperature in Fahrenheit is {:08.4f} F'.format(F))
    
C2F()
Enter temperature in degrees Centigrade: 32.4536
Temperature in Fahrenheit is 090.4165 F
In [67]:
def sum_primes(n):
    sum_p = 0
    for n in range(2, n + 1):
        if all(n % i for i in range(2, n)):
            sum_p += n
    print('The sum of the primes up to {:,} is {:,}'.format(n, sum_p))

sum_primes(100)
The sum of the primes up to 100 is 1,060

2.7.4 Write an interactive Python program to play a “guess the number” game. The computer should think of a random natural number between 1 and 20 and the user (player) has to try to guess the number within six attempts. The program should tell the player if the guess is too high or too low.

In [68]:
# Guess the number game.
import random # Import the random module.

num_guesses = 0
name = input('Hi! What is your name? ')
number = random.randint(1, 20) # A random integer between 1 and 20.
print('Welcome, {}! I am thinking of an integer between 1 and 20.'.format(name))

while num_guesses < 6:
    guess = int(input('Take a guess and type the integer? '))
    num_guesses += 1

    if guess < number:
        print('Your guess is too low.')
    if guess > number:
        print('Your guess is too high.')
    if guess == number:
        break

if guess == number:
    print('Well done {}! You guessed my number in {} guesses!'.format(name, num_guesses))
else:
    print('Sorry, you lose! The number I was thinking of was {}'.format(number))
Hi! What is your name? Stephen
Welcome, Stephen! I am thinking of an integer between 1 and 20.
Take a guess and type the integer? 10
Your guess is too high.
Take a guess and type the integer? 5
Your guess is too high.
Take a guess and type the integer? 3
Well done Stephen! You guessed my number in 3 guesses!

2.7.5 Consider Pythagorean triples, positive integers $a,b,c$, such that $a^2+b^2=c^2$. Suppose that $c$ is defined by $c=b+n$, where $n$ is also an integer. Write a Python program that will find all such triples for a given value of $n$, where both $a$ and $b$ are less than or equal to a maximum value, $m$, say. For the case $n=1$, find all triples with $1 \leq a \leq 100$, and $1 \leq b \leq 100$. For the case $n=3$, find all triples with $1 \leq a \leq 200$ and $1 \leq b \leq 200$.

In [69]:
# Pythagorean triples.
import math
def pythagorean_triples(i):
    for b in range(i):
        for a in range(1, b):
            c = math.sqrt( a * a + b * b)
            n = 1
            if c - b == n:
                print(a, b, int(c))
            
pythagorean_triples(101)
3 4 5
5 12 13
7 24 25
9 40 41
11 60 61
13 84 85
In [70]:
# Pythagorean triples.
import math
def pythagorean_triples(i):
    for b in range(i):
        for a in range(1, b):
            c = math.sqrt( a * a + b * b)
            n = 3
            if c - b == n:
                print(a, b, int(c))
            
pythagorean_triples(201)
9 12 15
15 36 39
21 72 75
27 120 123
33 180 183
© Copyright 2019-2021, Dr Stephen Lynch FIMA SFHEA