Complete the code to convert a dense matrix to a CSR sparse matrix.
from scipy.sparse import csr_matrix import numpy as np dense_matrix = np.array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) sparse_matrix = csr_matrix([1]) print(sparse_matrix)
The csr_matrix function converts a dense numpy array into a CSR sparse matrix format.
Complete the code to convert a CSR sparse matrix back to a dense numpy array.
from scipy.sparse import csr_matrix import numpy as np sparse_matrix = csr_matrix([[0, 0, 1], [1, 0, 0], [0, 2, 0]]) dense_matrix = sparse_matrix.[1]() print(dense_matrix)
todense() which returns a matrix, not a numpy array.to_numpy().The toarray() method converts a sparse matrix to a dense numpy array.
Fix the error in the code to convert a COO sparse matrix to CSC format.
from scipy.sparse import coo_matrix row = [0, 3, 1, 0] col = [0, 3, 1, 2] data = [4, 5, 7, 9] coo = coo_matrix((data, (row, col)), shape=(4, 4)) csc = coo.[1]() print(csc)
tocsr() which converts to CSR format instead.toarray() or todense() which convert to dense formats.The tocsc() method converts a COO sparse matrix to CSC format.
Fill both blanks to create a dictionary comprehension that maps each word to its length only if the length is greater than 3.
words = ['data', 'is', 'fun', 'and', 'powerful'] lengths = {word: [1] for word in words if [2] print(lengths)
The dictionary comprehension maps each word to its length using len(word) only if the length is greater than 3, checked by len(word) > 3.
Fill all three blanks to create a dictionary comprehension that maps each word in uppercase to its length only if the length is greater than 2.
words = ['cat', 'a', 'dog', 'elephant'] result = { [1]: [2] for word in words if [3] } print(result)
The dictionary comprehension maps each word in uppercase (word.upper()) to its length (len(word)) only if the length is greater than 2 (len(word) > 2).