Follows are practice problems on various topics we covered in the course. These will make you familar with the Python language and being able to practice writing programs is invaluable.
Write a Python program to calculate the volume of a sphere with radius 6.
import numpy as np
# set the radius of the sphere
r = 6
# calculate the volume
volume = (4/3)*np.pi*r**3
Write a Python program to test whether a number is within 100 of 1000 or 2000.
def near_thousand(n):
'''
This function checks whether a number is within 100 of 1000 or 2000.
The function returns the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.
Parameters
----------
n : int, float, complex
One-electron orbital of electron at r1.
Returns
-------
((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100)) : int
absolute value of number
'''
return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))
print(near_thousand(1100))
Write a Python program to calculate the sum of three given numbers. If all three values are equal then return three times their sum.
def sum_thrice(x, y, z):
'''
This function takes three numbers and calculates their sum.
If all three inputs are equal their sum is returned
'''
# add the three numbers together
sum = x + y + z
# catch if all three numbers are equal
if x == y == z:
sum = sum * 3
return sum
print(sum_thrice(1, 2, 3))
Write a Python program to find whether a given number is even or odd and print out an appropriate message.
# specify a integer number
num = 2
# calculate the remainder to see if it is divisible by num
mod = num % 2
# print suitable message
if mod > 0:
print("This is an odd number.")
else:
print("This is an even number.")
Write a Python program that will accept the base and height of a triangle and compute the area.
# input the base and height of triangle
base = 5
height = 8
# calculate the area of the triangle
area = (1/2) * base * height
print("area = ", area)
Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5.
def equal_sum(x, y):
'''
This function tests whether or not two numbers are equal or their sum or difference is 5.
Parameters
----------
x : int
First number to compare
y : int
Second number to compare
Returns
-------
True/False : Boolean
Whether or not the comparison is True or False
'''
if x == y or abs(x-y) == 5 or (x+y) == 5:
return True
else:
return False
print(equal_sum(7, 2))
print(equal_sum(27, 53))
Given variables x=10 and y=60, write a Python program to print "10+60=70" as a string. Make this program generic for any variable values.
# specify the input values of x and y
x = 10
y = 60
# print the sum
print("{} + {} = {}".format(x, y, x + y))
Write a Python program to filter the positive numbers from a list.
# create a list of numbers
list1 = [11, -21, 0, 45, 66, -93]
# iterating each number in list
for num in list1:
# checking condition
if num >= 0:
print(num, end = " ")
Write a function that takes an integer minutes and converts it to seconds.
e.g.
convert_to_secs(5) -> 300
def convert_to_secs(n):
'''
This function takes an integer minutes and converts it into seconds.
Parameters
----------
n : int
The number of minutes
Returns
-------
None
'''
# multiply the minutes by 60 to compute the seconds
seconds = n * 60;
print("{} minutes is equal to {} seconds".format(n, seconds))
# specity the number of minutes
n = 5
# call the function
convert_to_secs(n)
Write a function, add_it_up()
, that takes a single integer as input and returns the sum of the integers from zero to the input parameter.
The function should return 0 if a non-integer is passed in.
def add_it_up(n):
'''
This function takes an integer input and computes the sum of the integers from 0 to the input value.
We build the list of integers using range and call sum to add them together.
We use tryand except here which you might not have seen before, but it is similar to a if statement:
' try this part of the code and if it can be evaluated without error then continue with the program. If it returns an error run the code in the exception part'
Parameters
----------
n : int
an integer input
Returns
-------
result : int
The result of the summation, or 0 if a float is passed to the function
'''
# use try and except t
try:
result = sum(range(n + 1))
except TypeError:
result = 0
return result
# call the function
add_it_up(4)
Create a function that takes a string and returns it as an integer.
# specify your string
string = '34'
# test whether or not
try:
numerical_or_not = int(string)
except:
numerical_or_not = "Your string is not numerical so cannot be converted to an integer"
print(numerical_or_not)
Create a function that takes a list containing only numbers and return the first element.
def only_numbers(lst):
'''
This function checks if a list contains only numbers. If it does it will then return the first item from that list.
We use the following commands:
isinstance : The isinstance() function returns True if the specified object is of the specified type, otherwise False. Here we check for integer or float.
all : The all() function returns True if all items in an iterable are true, otherwise it returns False.
Parameters
----------
lst : list
A list of numbers
Returns
-------
lst[0] : int/float
The value of the first item in the list
'''
# test if the list contains only numbers
if all(isinstance(e, (int, float)) for e in lst):
pass
else:
return "Your list does not contain only numbers!"
return lst[0]
lst = [1,2,3,4,5]
print(only_numbers(lst))
lst2 = [1,2,'string',4,5]
print(only_numbers(lst2))
Create a function that takes a list of numbers. Return the largest number in the list.
def return_max(lst):
'''
Returns the largest item in a list
Parameters
----------
lst : list
A list of numbers
Returns
-------
max(lst) : int/float
The largest number in the list
'''
return max(lst)
# specify a list of numbers
lst = [1,30,681,104]
return_max(lst)
Create a function that returns True
if an integer is divisible by 5, and False
otherwise.
def div_by_5(n):
'''
Returns True if a number is divisible by 5, False if not.
Parameters
----------
n : int
The integer number to divide by 5
Returns
-------
True/False : Boolean
'''
if n % 5 == 0:
return True
else:
return False
print(div_by_5(5))
Create a function that takes an angle in radians and returns the corresponding angle in degrees.
import numpy as np
def convert_to_rad(theta_rad):
'''
Converts an angle in radian to an angle in degrees.
To convert from radians to degrees we divide by Pi and multiply by 180.
Parameters
----------
theta_rad : int/float
The angle in radians to be converted
Returns
-------
theta_deg : int/float
The converted angle in degrees
'''
theta_deg = theta_rad/np.pi * 180
return theta_deg
convert_to_rad(2*np.pi)
Write a function that takes a list and a number as arguments. Add the number to the end of the list, then remove the first element of the list. The function should then return the updated list.
e.g.
next_in_line([5, 6, 7, 8, 9], 1) ➞ [6, 7, 8, 9, 1]
def next_in_line(lst, num):
'''
This function takes a number and appends it to the supplied list.
It then removes the first item from the list.
Parameters
----------
lst : list
A list of data
num : int/float
A number to append to the list
Returns
-------
lst : int, float, string, bool
The first item from the list
'''
# add the number to the end of the list
lst.append(num)
# remove the first item from the list using the del command
del lst[0]
return lst
# define a list of numbers
lst = [5, 6, 7, 8, 9]
# define a number to append to the list
num = 1
# call the function
next_in_line(lst, num)
Write a function that takes coordinates of two points on a two-dimensional plane and returns the length of the line segment connecting those two points.
e.g.
line_length([0, 0], [1, 1]) ➞ 1.41
def line_length(pt1, pt2):
'''
Returns the length of the line segment between two points.
This is calculated as the following
sqrt((x2 - x1) ^2 + (y2 - y1)^2))
Parameters
----------
x : list
list of x coordinates
y : list
list of y coordinates
Returns
-------
np.sqrt((pt1[1] - pt2[0])**2 + (pt1[1] - pt2[1])**2) : int, float
The length of the line segment
'''
return ((pt1[1] - pt2[0])**2 + (pt1[1] - pt2[1])**2)**(1/2)
line_length([0, 0], [1, 1])
Create a function that takes two parameters and, if both parameters are strings, add them as if they were integers or if the two parameters are integers, concatenate them. If the two parameters are different data types, return None.
e.g.
silly_addition(1, 2) -> "12"
silly_addition("1", "2") -> 3
def silly_addition(param1, param2):
'''
Takes two parameters and, if both parameters are strings, adds them as if they were integers
If the two parameters are integers, concatenates them.
Parameters
----------
param1 : int, str
The first of the parameters
param2 : int, str
The second of the parameters
Returns
-------
int, str, None : The output of the comparison
'''
if (type(param1) == str) and (type(param2) == str):
return int(param1) + int(param2)
elif (type(param1) == int) and (type(param2) == int):
return str(param1) + str(param2)
else:
return None
silly_addition("1", "2")
Write a program that checks whether a number is a palindrome (reads the same forwards as backwards.
e.g.
is_it_palindrome(1331) -> Yes!
is_it_palindrome(4983) -> No!
"""
1. The value of the integer is stored in a temporary variable.
2. A while loop is used and the last digit of the number is obtained by using the modulus operator.
3. The last digit is then stored at the one’s place, second last at the ten’s place and so on.
4. The last digit is then removed by dividing the number with 10.
5. This loop terminates when the value of the number is 0.
6. The reverse of the number (rev) is then compared with the integer value stored in the temporary variable.
7. If both are equal, the number is a palindrome.
8. If both aren’t equal, the number isn’t a palindrome.
Another, simpler solution using strings is presented after the first implementation
"""
n = 1010101
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
#
# using strings
#
n2 = 1010101
# convert the number to a string
str_n = str(n2)
# reverse the characters in the string
reverse_str = str_n[::-1]
# compare reversed string with the converted number string
if str_n == reverse_str:
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
The Collatz conjecture states that the following sequence always reaches 1:
Write a Python program to test this conjecture.
e.g.
n = 5 -> 5 16 8 4 2 1
# create an empty list
i = []
def collatz(n):
'''
Test the Collatz conjecture
1. Start with a positive integer n.
2. The next number in the sequence is $\frac{n}{2}$ if $n$ is even and $3n + 1$ if $n$ is odd.
We solve this using recursion, i.e. the function calls it self repeatedly until n == 1 when it terminates.
Parameters
----------
n : int
An integer number, the starting value for the Collatz conjecture
Returns
-------
collatz(n), i : func, int
Either the function call itself and returns its own output or returns integer if terminates
'''
if n == 1:
return i
if n % 2 == 0:
n = n // 2
else:
n = ((3*n) + 1)
# add the number to the empty list
i.append(n)
return collatz(n)
print(collatz(5))
Write a NumPy program to create a $3 \times 3$ identity matrix.
import numpy as np
np.identity(3)
Write a NumPy program to find the number of rows and columns of a given matrix.
import numpy as np
# create a randomly populated matrix of dimensions 5 x 5
mat = np.random.randn(5,5)
# print the arrays' shape
print(mat.shape)
Write a NumPy program to convert an array to a string
type.
import numpy as np
# create a randomly populated matrix of dimensions 5 x 5
mat = np.random.rand(5,5)
# change the type of the arrya using `astype`
mat.astype(str)
Write a NumPy program to compute the multiplication of two arrays you define.
import numpy as np
# create first array
array1 = np.random.rand(10,10)
# create second array
array2 = np.random.rand(10,10)
np.matmul(array1, array2)
Write a NumPy program to compute the determinant of a given square array.
import numpy as np
# create a random array
array = np.random.rand(10,10)
# call `det` from the numpy linalg library (linear algebra) which calcuates the determinant
np.linalg.det(array)
Write a NumPy program to compute the inverse of a given array.
import numpy as np
# create a random array
array = np.random.rand(10,10)
# call `inv` from the numpy linalg library (linear algebra) which calculates the matrix inverse
np.linalg.inv(array)
Write a NumPy program to compute the sum of the diagonal element of a given array.
import numpy as np
# create a random array
array = np.random.rand(10,10)
# call trace which adds up the diagonal numbers in an array. i.e. calculates the trace of a matrix
np.trace(array)
Consider the following array:
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Write a program to extract the odd numbers.
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# check if the numbers leave a remainder when divided by 2
arr[arr % 2 == 1]
Convert a 1D array to a 2D array with 2 rows.
arr = np.array([0,1, 2, 3, 4, 5, 6, 7, 8, 9])
# use the respahe command to resize it to 5 columns and 2 rows
arr.reshape(2,5)
Create two arrays and stack them vertically and horizontally.
import numpy as np
# create two random arrays
array1 = np.random.rand(5,5)
array2 = np.random.rand(5,5)
# vertically stack using vstack
print(np.vstack([array1, array2]))
# horizontally stack using hstack
print(np.hstack([array1, array2]))
Use the following line of code to generate an array of random numbers and extract all numbers between 5 and 10.
arr = np.array([2, 6, 1, 9, 10, 3, 27])
# build array
np.array([2, 6, 1, 9, 10, 3, 27])
# apply conditions directly to the array as an index condition
arr[(arr >= 5) & (arr <= 10)]
Find the mean, median and standard deviation of an array you create.
import numpy as np
# create random 10 x 10 array
arr = np.random.rand(10,10)
# calculate the mean by calling .mean()
print("mean is {}".format(arr.mean()))
# calculate the standard deviation by calling .std()
print("Standard deviation is {}".format(arr.std()))
The following Python code snippet will create a $10 \times 10$ array filled with random numbers
arr = np.random.rand(10, 10)
Extract the $3 \times 3$ sub-matrix starting from the top left corner.
Example of a $2 \times 2$ sub-matrix extracted from a $3 \times 3$ matrix:
$$ \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{pmatrix} \rightarrow \begin{pmatrix} 1 & 2 \\ 4 & 5 \\ \end{pmatrix} $$
import numpy as np
arr = np.random.rand(10, 10)
arr[:7, :7]
Transpose the array, arr
, from question 13.
arr = np.random.rand(10, 10)
# transpose using .T
arr.T
Given a 1D array, negate all elements which are between 3 and 8.
import numpy as np
# create a integer array
arr = np.array([1,8,3,84,2,7,11,5])
# setup the conditions
m = (arr >= 3 ) & (arr <= 8)
# apply the conditions to the array and multipl by -1 for elements which satisfy the condition
arr[m] *= -1
# print the new array with the correct elements negated
print(arr)
Calculate the eigenvalues and eigenvectors of the following array:
$$ \begin{pmatrix} 1 & 2 \\ 2 & 3 \\ \end{pmatrix} $$
import numpy as np
# create array
arr = np.array([[1,2],
[3,4]])
# call the eigenvalue command, `eig` from the numpy linalg module
np.linalg.eig(arr)
Write a NumPy program to add a new row to an empty NumPy array.
import numpy as np
create an empty integer array
arr = np.empty((0,3), int)
print("Empty array:") print(arr)
add a new row
arr = np.append(arr, np.array([[10,20,30]]), axis=0) print("After adding a new row:") print(arr)