Complete the code to add a tensor and a scalar using broadcasting.
import torch a = torch.tensor([1, 2, 3]) b = 5 result = a [1] b print(result)
Adding a tensor and a scalar uses broadcasting, so + correctly adds 5 to each element.
Complete the code to multiply a 2D tensor by a 1D tensor using broadcasting.
import torch a = torch.tensor([[1, 2, 3], [4, 5, 6]]) b = torch.tensor([1, 0, 1]) result = a [1] b print(result)
Multiplying a 2D tensor by a 1D tensor broadcasts the 1D tensor across rows, so * is the correct operator.
Fix the error in the code by completing the broadcasting operation correctly.
import torch a = torch.tensor([[1, 2, 3], [4, 5, 6]]) b = torch.tensor([1, 2]) result = a [1] b print(result)
Adding a (2,3) tensor and a (2,) tensor broadcasts the smaller tensor across columns, so + works correctly.
Fill both blanks to create a tensor of shape (3, 4) by broadcasting a (3, 1) tensor with a (1, 4) tensor.
import torch a = torch.tensor([[1], [2], [3]]) # shape (3, 1) b = torch.tensor([[4, 5, 6, 7]]) # shape (1, 4) result = a [1] b print(result.shape) # should print torch.Size([2])
Multiplying tensors with shapes (3,1) and (1,4) broadcasts to (3,4). The shape printed is (3, 4).
Fill all three blanks to create a dictionary comprehension that maps each word to its length if the length is greater than 3.
words = ['apple', 'bat', 'carrot', 'dog'] lengths = { [1]: [2] for word in words if len(word) [3] 3 } print(lengths)
The dictionary comprehension maps each word to its len(word) only if the length is greater than 3.