-
Notifications
You must be signed in to change notification settings - Fork 1
/
week04_solutions.txt
175 lines (134 loc) · 4.22 KB
/
week04_solutions.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
###week04_ex1_start_py
import numpy as np
# Create the matrix M
M = np.array([[9, 3, 0], [-2, -2, 1], [0, -1, 1]])
# Create the vector y
y = np.array([0.4, -3, 0.3])
###week04_ex1_end
###week04_ex2_start_py
import numpy as np
def dot_prod(u, v):
'''
Returns the dot product of vectors u and v.
'''
return np.sum(u * v)
###week04_ex2_end
###week04_ex3_start_py
# Assuming we still have M and y in memory from Exercise 1...
x = np.linalg.solve(M, y)
# Print the norms
print(f'The 2-norm of x is {np.linalg.norm(x, 2)}.')
print(f'The infinity-norm of x is {np.linalg.norm(x, np.inf)}.')
###week04_ex3_end
###week04_ex4_start_py
# Create a random number generator
rng = np.random.default_rng()
# Create a random 3x5 matrix of integers between 1 and 10
A = rng.integers(1, 11, size=[3, 5])
print(A, '\n')
# Create a Boolean array the same shape as A, with True where the corresponding
# elements of A are smaller than 5, and False elsewhere
A5 = A < 5
print(A5, '\n')
# Use A5 to return all elements of A smaller than 5 (in a 1D array)
print(A[A5], '\n')
# Display the rows of A starting at row 1, and columns ending at column 2
print(A[1:, :3], '\n')
# Display the elements of that sub-matrix which are smaller than 5
print(A[1:, :3][A5[1:, :3]], '\n')
# Reassign all elements of A which are greater than or equal to 5 with the value 100
A[np.logical_not(A5)] = 100
print(A)
###week04_ex4_switch_md
This is an example of how you can use **Boolean indexing** to extract elements of an array which fulfill certain conditions.
###week04_ex4_end
###week04_ex5_start_py
import numpy as np
# Create a random number generator
rng = np.random.default_rng()
# Create a random matrix A with 2000x2000 elements between -1 and 1.05
n = 2000
A = (1.05 + 1) * rng.random([n, n]) - 1.
# Get the sum of all rows of A
row_sums = np.sum(A, axis=1)
# Display the proportion of rows with a positive sum
positive_sum_rows = np.sum(row_sums >= 0)
print(f'The probability that a row of A is positive',
f'is approximately {100 * positive_sum_rows / n : .1f}%.')
###week04_ex5_end
###week04_ex6_start_py
n = 4
# Initialise A with zeros
A = np.zeros([n, n])
# Loop over the rows...
for i in range(n):
# Loop over the columns...
for j in range(n):
if i < j:
A[i, j] = i + 2*j
else:
A[i, j] = i * j
print(A)
###week04_ex6_end
###week04_ex7_start_py
# Create an x-axis with 1000 points
x = np.linspace(-np.pi, np.pi, 1000)
# Evaluate the functions at all these points
f1 = np.sin(x)
f2 = np.tan(0.49 * x)
f3 = np.sin(x) * np.cos(2*x)
# Create the plots in the same axes
plt.plot(x, f1, 'r-.')
plt.plot(x, f2, 'g:')
plt.plot(x, f3, 'b--')
# Display the plot
plt.show()
###week04_ex7_end
###week04_ex8_start_py
import matplotlib.pyplot as plt
import numpy as np
# Create an x-axis with 1000 points
x = np.linspace(-np.pi, np.pi, 1000)
# Evaluate the functions at all these points
f1 = np.sin(x)
f2 = np.tan(0.49 * x)
f3 = np.sin(x) * np.cos(2*x)
# Create a figure with 3 subplots
fig, ax = plt.subplots(1, 3, figsize=(10, 4))
# Plot each function in a different subplot
ax[0].plot(x, f1, 'r-.')
ax[1].plot(x, f2, 'g:')
ax[2].plot(x, f3, 'b--')
# Display the plot
plt.show()
###week04_ex8_end
###week04_ex9_start_py
# first approach: using 'readline'
with open('mytextfile.txt','r') as myfile:
# Initialise an empty list to store the lines
all_lines = []
# if line is empty, the end of file is reached
while True:
# use readline to read the next line
line = myfile.readline()
# Break the loop when we reach an empty line (remember Boolean casting!)
if not line:
break
# Append to the list if we still have non-empty lines
all_lines.append(line)
# second approach: using 'readlines'
with open('mytextfile.txt','r') as myfile:
all_lines = myfile.readlines()
print(all_lines)
###week04_ex9_end
###week04_ex10_start_py
# Read the file, store the lines in a list
with open('mytextfile.txt', 'r') as myfile:
all_lines = myfile.readlines()
# Edit and write each new line to a new file
with open('textfile_linenumber.txt', 'w') as newfile:
count = 1
for line in all_lines:
newfile.write(f'{count}: {line}')
count += 1
###week04_ex10_end