Complete the code to create a 3x3 sparse matrix with scipy.
from scipy.sparse import [1] matrix = [1]([[0, 0, 1], [1, 0, 0], [0, 0, 0]]) print(matrix)
The csr_matrix is a common sparse matrix format for efficient arithmetic and matrix vector operations.
Complete the code to convert a dense numpy array to a sparse matrix.
import numpy as np from scipy.sparse import csr_matrix dense = np.array([[0, 2, 0], [3, 0, 0], [0, 0, 4]]) sparse = csr_matrix([1]) print(sparse)
To convert a dense numpy array to a sparse matrix, pass the dense array to csr_matrix.
Fix the error in the code to add two sparse matrices correctly.
from scipy.sparse import csr_matrix A = csr_matrix([[1, 0], [0, 2]]) B = csr_matrix([[0, 3], [4, 0]]) result = A [1] B print(result.toarray())
To add two sparse matrices, use the + operator.
Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.
words = ['data', 'science', 'ai', 'ml', 'python'] lengths = {word: [1] for word in words if len(word) [2] 3} print(lengths)
< instead of > in the condition.The dictionary comprehension maps each word to its length if the word length is greater than 3.
Fill all three blanks to create a filtered dictionary with uppercase keys and values greater than 2.
data = {'a': 1, 'b': 3, 'c': 5, 'd': 2}
filtered = { [1]: [2] for k, v in data.items() if v [3] 2 }
print(filtered)This dictionary comprehension creates keys as uppercase letters and includes only items where the value is greater than 2.