0
0
PyTorchml~10 mins

__getitem__ and __len__ in PyTorch - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define the __len__ method that returns the size of the dataset.

PyTorch
def __len__(self):
    return [1]
Drag options to blanks, or click blank then click option'
Aself.data
Bself.length
Clen(self.data)
Dlen(self)
Attempts:
3 left
💡 Hint
Common Mistakes
Returning self.data directly instead of its length.
Using len(self) which causes infinite recursion.
2fill in blank
medium

Complete the code to define the __getitem__ method that returns the data item at the given index.

PyTorch
def __getitem__(self, index):
    return [1]
Drag options to blanks, or click blank then click option'
Aself.data.get(index)
Bself[index]
Cself.get(index)
Dself.data[index]
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to call self.get(index) which is not defined.
Using self[index] which causes recursion.
3fill in blank
hard

Fix the error in the __getitem__ method to correctly return the label for the given index.

PyTorch
def __getitem__(self, index):
    data = self.data[index]
    label = self.labels[1]
    return data, label
Drag options to blanks, or click blank then click option'
A[index]
B(index)
C{index}
D.index
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses which calls the object as a function.
Using braces which is invalid syntax for indexing.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each word to its length only if the length is greater than 3.

PyTorch
lengths = {word: [1] for word in words if len(word) [2] 3}
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in the condition.
Mapping to word instead of its length.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps each uppercase key to its value only if the value is positive.

PyTorch
result = [1]: [2] for k, v in data.items() if v [3] 0}
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
C>
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using k instead of k.upper() for keys.
Using < instead of > in the condition.