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!}$.
2 - (3 + 6)
-7
2 * (5 - 8 * (3 + 6))
-134
2 * (2 - 2 * (3 - 6 + 5 * (4 - 7)))
76
(2 * (5 - 4 * (3 + 8))) / (3 * (4 - (3 - 5)))
-4.333333333333333
from math import *
(2 * 4**5) / (81 - factorial(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)$.
from sympy import *
sqrt(4 + 6**5 + factorial(5))
cos(0.8)
atan(-0.4)
log(87.95)
log10(725.345)
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}$.
from fractions import Fraction
Fraction(1, 3) * Fraction(1, 4) - Fraction(1, 5)
Fraction(-7, 60)
(Fraction(1, 3) - Fraction(2, 5))**3
Fraction(-1, 3375)
Fraction(1, 7) * Fraction(4, 23) / Fraction(37, 125)
Fraction(500, 5957)
from sympy import expand
expand((sqrt(2) - 3)**4)
from sympy import simplify
simplify((1 / (sqrt(2) + 3)))
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)$.
(cos(0.9))**2
round(log(8) - log10(56),5)
factorial(12)
fmod(5186, 8)
2.0
floor(5 * pi - 2 * exp(1))
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)$.
from sympy import *
x, y = symbols('x y')
factor(x**3 - y**3)
solve(x**2 - 7 * x - 30)
[-3, 10]
apart(3 * x / ((x - 1) * (x + 2) * (x - 5)))
trigsimp(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4)
expand((y - x - 3) * (x**2 - y + 4))
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$.
n = symbols('n')
limit((1 + 1 / n)**n, n, oo)
diff(3 * x**4 - 6 * x**3, x)
diff(3 * x**4 - 6 * x**3, x, 3)
integrate(x**2 - 2 * x - 3, (x, 0, 1))
(exp(x) * sin(x)).series(x , 1, 10)
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$.
summation(1 / n, (n, 1, oo))
summation(2 + 3 * (n - 1), (n, 1, 20))
summation(2 * 3**n, (n, 1, 20))
solve([2 * x - y - 9, 3 * x + y - 8] , [x, y])
{x: 17/5, y: -11/5}
solve([x**2 - y - 2, x + y - 1] , [x, y])
[(-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$.
A = Matrix([[-1, 2, 4],[0, 3, 2],[1, 4, 6]])
B = Matrix([[2, 3, 3],[0, 3, 0],[-6, 1, 1]])
3 * A - 5 * B
A * B
A**(-1)
((A * B)).col(0)
(A * B).T
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]]$.
list(range(5, 201, 1)); # Semi-colon suppresses output.
list(range(-4, 201, 2));
list(range(3, 301, 3));
list(range(30, -4, -3))
[30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, -3]
[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.
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]])
A.sum(axis = 1)
array([16, 41, 71])
A.sum(axis = 0)
array([ 1, 38, 15, 12, 8, 1, 29, 17, 13, -6])
A.min(axis = 1)
array([-9, -1, 0])
A.max(axis = 0)
array([ 2, 24, 8, 6, 12, 2, 14, 9, 8, 2])
A.cumsum(axis = 1)
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)$.
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()
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()
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()
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()
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)$.
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()
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.
def sgn(x):
if x < 0:
return -1
elif x == 0:
return 0
else:
return 1
sgn(-35)
-1
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
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
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
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$.
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())
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.
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
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.
# 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$.
# 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
# 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