Week 3
Week 3
Out[14]: True
----------------------------------------------------------------
-----------
TypeError Traceback (most recent
call last)
Cell In [17], line 1
----> 1 d[[1, 2]] = 3
Checking if a number belongs to a list takes time proportional to the length of the
list.
Checking if a number is a dictionary key takes a constant amount of time,
independent of the number of keys.
Convenience.
----------------------------------------------------------------
-----------
ZeroDivisionError Traceback (most recent
call last)
Cell In [21], line 1
----> 1 average_finder([[1, 2, 3], [10, -10], []])
In [22]: l = []
try:
mean = sum(l) / len(l)
except Exception as e:
print("something went wrong")
print("reason:", e)
mean = 0
print(mean)
In [25]: divide(2, 0)
----------------------------------------------------------------
-----------
Exception Traceback (most recent
call last)
Cell In [25], line 1
----> 1 divide(2, 0)
In [ ]: import math
math.sin(math.pi / 2)
Out[29]: 2
import numpy as np
What is NumPy for?
"The fundamental package for scientific computing with Python"
Used for all kind of numerical computation, principally numerical linear algebra.
Widely used in science and industry
NumPy arrays
Represent lists, vectors/matrices, higher-dimensional analogues.
Similar to Python lists, but with methods for numerical linear algebra.
In [ ]: import numpy as np
a = np.array([1, 2, 3])
a.shape # (3, ), which is a tuple of length 1
[[1 2]
[3 4]]
Accessing array elements
Similar to Python list accesses.
In [ ]: a = np.array([1, 2, 3])
a[0]
Out[32]: 2
In [35]: 2 * a
Out[36]: array([[0],
[0]])
Out[37]: array([[4],
[1]])
Array equality
In [38]: v = np.array([[1], [2]]) # 2x1 column vector
u = np.array([[1], [3]])
v == u
In [39]: np.array_equal(v, u)
Out[39]: False
Matrix multiplication
Use @ to matrix multiply arrays.
Out[40]: array([[3],
[3]])
In [41]: v @ A
----------------------------------------------------------------
-----------
ValueError Traceback (most recent
call last)
Cell In [41], line 1
----> 1 v @ A
In [ ]: v + u # matrix/vector addition
Vectorizing
NumPy has its own version of functions like sin, cos, exp...
In [ ]: import math
math.sin(a)
Use import matplotlib.pyplot as plt for simple plots.
Simple matplotlib plots
plt.plot(xs, ys) plots the points with coordinates (xs[0], ys[0]) , (xs[1],
ys[1]) , ... and joins them with straight lines.