0% found this document useful (0 votes)
5 views11 pages

Python Exercises: NumPy Arrays Basics

Module 3: Vector Programming provides a series of exercises for practicing Python and NumPy skills, covering topics such as array creation, manipulation, and mathematical operations. Exercises include creating specific array shapes, implementing functions for matrix operations, and applying concepts like Newton's Second Law and Purchasing Power Parity. The module emphasizes hands-on coding practice to deepen understanding of vector programming concepts.

Uploaded by

theocoronges
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Python Exercises: NumPy Arrays Basics

Module 3: Vector Programming provides a series of exercises for practicing Python and NumPy skills, covering topics such as array creation, manipulation, and mathematical operations. Exercises include creating specific array shapes, implementing functions for matrix operations, and applying concepts like Newton's Second Law and Purchasing Power Parity. The module emphasizes hands-on coding practice to deepen understanding of vector programming concepts.

Uploaded by

theocoronges
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 3: Vector Programming v1.

Try the exercises below to practice the concepts from this module. They are
numbered by session. I recommend deactivating Gemini first (and any other AI
helper) and attempting the exercises on your own. This approach will help you
gain a deeper understanding of how Python works.

Each exercise includes one or more examples of how your solution should func-
tion. Keep in mind that a good Python program should work under any cir-
cumstances, or at the very least, provide an informative message when it fails.
Always test your code in as many scenarios as you can imagine!
√ For instance,
if the exercise asks you to write a function that computes x, does your code
handle decimal numbers? What if x is negative?

1 Arithmetic Array Operations


Exercise 1.1: Creating an Array
Write a code that creates a NumPy array of shape (3, 3) such that:

• All elements are ones.


• The four corner elements are zeros.

The resulting array should look like this:


 
0 1 0
1 1 1
0 1 0

Exercise 1.2: Positive-Negative Array


Write a code that creates a NumPy array of shape (3, 3) such that:

• Elements in even positions contain 1.


• Elements in odd positions contain −1.

The resulting array should look like this:


 
1 −1 1
−1 1 −1
1 −1 1

Exercise 1.3: Binary Array


Write a code that creates a NumPy array of shape (4, 4) such that:

• Even-indexed rows (0 and 2) contain only zeros.


• Odd-indexed rows (1 and 3) contain only ones.

The resulting array should look like this:


Module 3: Vector Programming v1.0

 
0 0 0 0
1 1 1 1
 
0 0 0 0
1 1 1 1

Exercise 1.4: Inner array


Implement a function inner_matrix(A) that receives a square numpy array A
with shape n × n and returns its inner matrix:

• For a 3 × 3 array, it should return the single central element.

• For a 4 × 4 array, it should return the 2 × 2 matrix located in the center.


• In general, for an n × n array (n > 2), it should return the submatrix
obtained by removing the outermost row and column.

If the operation cannot be performed (if A is not square or its size is less
than 3 × 3), the function must print a customized warning message.
Sample input 1: A = [Link]([[1, 2], [3, 4]])
inner_matrix(A)
Expected result 1: Cannot perform the operation between matrices.
Cause: Matrix is too small (must be larger than 2x2).

Sample input 2: A = [Link]([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],
[13, 14, 15, 16]])
inner_matrix(A)
Expected result 2: C = [[6 7] [10 11]]
Module 3: Vector Programming v1.0

Exercise 1.5: Row and Column Permutation


Write two functions to manipulate the structure of a NumPy array:

1. reverse_rows(A): returns a new array with the order of its rows reversed.
The first row becomes the last, the second becomes the second to last, and
so on.

2. reverse_columns(A): returns a new array with the order of its columns


reversed. The first column becomes the last, the second becomes the
second to last, and so on.

Sample input: A = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
reverse_rows(A)
reverse_columns(A)
Expected result: C = [[10 11 12] [ 7 8 9] [ 4 5 6] [ 1 2 3]]
D = [[ 3 2 1] [ 6 5 4] [ 9 8 7] [12 11 10]])

Exercise 1.6: Customized permutation


Write a function custom_permute(A, axis, i, j) that receives:

• A: a NumPy array.
• axis: an integer that specifies whether to swap rows (0) or columns (1).

• i and j: integers representing the indices of the rows or columns to swap.

The function should return a new array with the two specified rows or
columns exchanged.

Sample input: A = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])


custom_permute(A, 0, 0, 2)
custom_permute(A, 1, 0, 2)
Expected result: C = [[7 8 9] [4 5 6] [1 2 3]]
D = [[3 2 1] [6 5 4] [9 8 7]]
Module 3: Vector Programming v1.0

Exercise 1.7: Arrays Calculator


Create a function array_operation(A, B, operation) that receives two NumPy
arrays (A and B) and a basic operation to apply to them (sum, subtract, mul-
tiply, divide and power).
If the operation cannot be performed, the function must print the mes-
sage: Cannot perform the operation between matrices. Cause: <error
message>
Sample input 1: A = [Link]([1, 2] ,[3, 4]); B = [Link]([0, 2] ,[1, 3])
array_operation(A, B, [Link])
Expected result 1: Cannot perform the operation between matrices.
Cause: The array in the denominator contains zeros.
Sample input 2: A = [Link]([1, 2] ,[3, 4]); B = [Link]([2, 4] ,[3, 5]);
array_operation(A, B, [Link])
Expected result 2: C = [[3 6] [6 9]]

Exercise 1.8: Array and Vector Operations


Consider the following three examples of matrices and vectors. For each case,
perform the indicated operations and explain why the operation can or cannot
be performed.

1. M = [Link]([[2, 8], [5, 1], [3, 7]]) v = [Link]([[4], [6], [9]])


2. M = [Link]([[1, 3, 5], [2, 4, 6]]) v = [Link]([10, 20, 30])
3. M = [Link]([[7, 2], [9, 4], [5, 8]]) v = [Link]([3, 6, 9])

Compute the following (when possible):

1. A = M + v
2. B = M * v
3. C = M**2 + 2*v

4. D = M * v + 2

Verify the shape of each valid result and interpret the meaning of the oper-
ations.
Module 3: Vector Programming v1.0

Exercise 1.9: Force Matrix from Masses and Accelerations


We have a vector that contains the masses of different objects and another vector
that contains several acceleration values.
Compute a 2-D NumPy array of forces according to Newton’s Second Law,
where each row represents the forces acting on one object for all given acceler-
ations.

Sample input: m = [Link]([2.0, 3.5, 1.2, 5.0])


a = [Link]([[1.0], [-2.0], [0.5]])
Expected result: F = [[ 2.0, 3.5 1.2 5.0] [ -4.0 -7.0 -2.4 -10.0]
[ 1.0 1.75 0.6 2.5]

Exercise 1.10: Exchange Rate Evolution under Inflation Differential


According to the Purchasing Power Parity (PPP) model, the nominal exchange
rate evolves as
S(t) = S0 e(πd −πf )t ,
and the real exchange rate is
Pt∗
q(t) = S(t) , Pt = eπd t , Pt∗ = eπf t .
Pt
If PPP holds, q(t) should remain approximately constant.

Write a function ppp_exchange(S0, pi_dom, pi_for, years) that computes


(without using any loop) and prints S(t), q(t), and ln S(t) for each year from 0
up to the value given in years. Round all results to five decimal places.

Sample input:
ppp_exchange(S0=1.10, pi_dom=0.04, pi_for=0.02, years=5)
Expected result:
Year 0: S = 1.10, q = 1.10, ln(S) = 0.0953
Year 1: S = 1.1222, q = 1.10, ln(S) = 0.1153
Year 2: S = 1.1449, q = 1.10, ln(S) = 0.1353
Year 3: S = 1.168, q = 1.10, ln(S) = 0.1562
Year 4: S = 1.1916, q = 1.10, ln(S) = 0.1753
Year 5: S = 1.2157, q = 1.10, ln(S) = 0.1953
Module 3: Vector Programming v1.0

Exercise 1.11: Intensity Variation and Brightness Analysis


Two matrices A and B represent the pixel intensity values (from 0 to 255) of a
grayscale image before and after applying a transformation.
Determine whether the overall brightness increased, decreased, whether any
pixels turned completely black, or if the changes are mixed.
Print one of the following messages depending on the results:
• "Brightness increased everywhere"

• "Brightness decreased everywhere"


• "Some pixels are completely black"
• "Brightness changes are mixed"

Sample input:
A = [Link]([[120, 100, 90],
[130, 110, 80]])
B = [Link]([[125, 105, 95],
[135, 115, 85]])
Expected result:
Brightness increased everywhere
Module 3: Vector Programming v1.0

2 Array Manipulation
Exercise 2.1: Rolling Spectral Energy Analysis
A telescope continuously records light intensity across four spectral bands (radio,
infrared, visible, and ultraviolet) for four regions of the sky. These values are
stored in a fixed 4 × 4 NumPy array A, where each column represents a spectral
band.
Because the system has limited memory, the matrix must always remain of
size 4 × 4. When new data arrives, the oldest band must be processed and
replaced.
Processing consists of multiplying all values in the first column to compute
the total spectral energy of that band, adding that product in a list and
then removing it and appending the next incoming band (a 1D NumPy ar-
ray) from the list new_vectors. This continues until all new bands have been
incorporated.

Sample input:
A = [Link]([[2, 3, 5, 7],
[1, 4, 6, 2],
[3, 2, 1, 5],
[2, 3, 4, 6]])
new_vectors = [
[Link]([3, 5, 2, 4]),
[Link]([6, 2, 1, 3])
]
Expected result:
Spectral energies: [12, 48, 120, 420, 120, 36]

Exercise 2.2: Rouché-Frobenius Theorem


A non-homogeneous system of linear equations Ax = b with n variables has a
solution if and only if the rank of its coefficient matrix A is equal to the rank
of its augmented matrix [A|b]. If there are solutions, we can find that:
• if rank(A) = n, the solution is unique,
• if rank(A) < n, there are infinite solutions.
Write a function rouche frobenius theorem(A, b) that prints a message
depending on the number of possible solutions for any system of linear equations.
Module 3: Vector Programming v1.0

Exercise 2.3: Image Superposition with Schrödinger’s Cat


In the realm of quantum mechanics, Schrödinger’s cat thought experiment poses
a scenario where a cat is simultaneously both alive and dead until it is observed.
As a nod to this concept, let’s create an image representation where both a live
cat and a skeletal cat are superimposed.
Start with this image: [Link]
[Link]. You can load it in Python by
using the functions in this notebook: [Link]
16fzoqKUZWERmKI0eBxCKXFO1JqC4C5t7/view?usp=drive_link

Produce an image where both the alive cat and the skeletal cat appear
superimposed by alternating the pixels from each image.
Module 3: Vector Programming v1.0

3 Numpy Random & Statistics


Exercise 3.1: Coin Tosses
You are in a contest. The host flips two fair coins in secret. They tell you that
at least one of the coins landed on heads. What is the probability that the other
coin landed on tails? Make one thousand simulations in Python to validate your
results.
Answer: The chance of the other being tails should be 66.6%.

Exercise 3.2: Random Walk


You are given a list of player names and a fixed number of steps X. Each player
begins at position 0 and performs a random walk of X steps. Write a function
random walks() that simulates this process. At each step, the player should
either move +1 or −1, chosen uniformly at random. After completing the walk
for each player, return a dictionary where each key is a player’s name, and the
corresponding value is that player’s final position.
Your function should accept the following arguments:

• players (positional): A list or tuple of player names.

• num steps (keyword): The number of steps for each player’s random walk
(same number for all of them), defaulting to 10.
• random seed (keyword): If provided, set the random seed to ensure re-
producible results.

Additionally, if a player’s name appears multiple times in the input list, append
a “-” to subsequent occurrences to ensure that all dictionary keys are unique.
For example, if “Alex” appears twice, the keys should be “Alex” and “Alex−”. If
“Bob” appears three times, the keys should be “Bob”, “Bob−”, and “Bob−−”.
See the code below for an example of input and output:
players = ["Alex", "Alex", "Bob", "Bob", "Bob", "Chia"]
x = 10
print(random_walks(players, num_steps=x))
# Example output (actual results will vary due to randomness):
# "Alex": 2, "Alex-": 0, "Bob": -1, "Bob-": -3, "Bob--": 0, "Chia": 4

Exercise 3.3: Approximating Pi with Monte Carlo


Consider a square with a circle inside it. We randomly generate points within
this square. The image below illustrates this with green points inside the circle
and red points outside.
To estimate the value of π, we use the Monte Carlo method. This involves
comparing the number of points inside the circle (green) to the total number of
points (green and red). The formula for approximating π is:
Module 3: Vector Programming v1.0

number of blue points


π ≈4×
total number of points
Write the monte carlo pi() function to approximate π. It should:

• Accept num points, the number of random points to create.


• Generate random points in a square with corners (-1, -1) and (1, 1).
• Count how many points fall inside the unit circle x2 + y 2 ≤ 1.

• Calculate π following the equation above.


• Return this estimated value of π.
Module 3: Vector Programming v1.0

4 Numpy Linear Algebra


Exercise 4.1: Coloured Image Compression
Following the example seen in class, write a Python function that takes as input
a 3D array representing an RGB image, and compresses it. In order to do so,
you can treat the RGB image as three separate images: one for each layer of
color (red, green, blue). Then, compress each layer individually by using either
eigen decomposition or SVD (as seen in class). Finally, the function returns the
eigenvalues and eigenvectors belonging to each RGB layer.

5 Numpy Vectorization
Exercise 5.1: Evolution of Assets
You purchased ten assets of the same kind, a year ago, for 150 euros each. The
value of a single asset varies daily following a normal distribution centered at
0.05 and with a standard deviation of 0.1 (meaning that, on average, the value
of the asset increases 0.05 euros a day!). Simulate the evolution of your assets
over a year, and compute the final total value of your wallet by the end of the
year under that simulation (adding the original value of your assets and their
daily variations).

You might also like