Python Review
Python Review
Basic of Python
• Collections
• List
Python Review • Tuple
A quick refresher • Set
• Dictionary
• NumPy (Matrix)
1
30-09-2023
2
30-09-2023
Loops
• #Basic for loop
Loops
• for i in range(5): • Second Method
print(i) • for i, name in enumerate(names):
• To iterate over a list
• names = ["Zach", "Jay", "Richard"] print(i, name)
• for name in names: • To iterate over a dictionary
print(name) • phonebook = {"Zach": "12-37", "Jay": "34-23"}
• To iterate over indices and values in a list
• # Way 1 • Iterate over keys
• for i in range(len(names)): • for name in phonebook:
• print(i, names[i]) print(name)
• print("---")
print("---")
3
30-09-2023
Precautions!!
NumPy – Array Dimensions - Shape • Vectors can be represented as 1-D arrays of shape (N,) or 2-D
arrays of shape (N, 1) or (1, N).
•print(x.shape) • (N,), (N, 1), and (1,N) are not the same.
•print(y.shape) • Matrices are generally represented as 2-D arrays of shape (M, N).
• Test the shape before you go further down with the program
•print() • a = np.arange(10)
•print(z) • b = a.reshape((5, 2))
• print(a)
•print(z.shape) • print()
• print(b)
4
30-09-2023
• W = np.array([[1, 2], [3, 4], [5, 6]]) • We can fix the above issue by transposing W.
• print(v.shape) • print(np.dot(W.T, v))
• print(W.shape) • print(np.dot(W.T, v).shape)
5
30-09-2023
Indexing in matrix
• x = np.random.random((3, 4))
• Selects all of x
• print(x[:])
• Selects the 0th and 2nd rows
• print(x[np.array([0, 2]), :])
• Selects 1st row as 1-D vector and and 1st through 2nd elements
• print(x[1, 1:3])
• Boolean indexing
• print(x[x > 0.5])
• 3-D vector of shape (3, 4, 1)
• print(x[:, :, np.newaxis])