0
0
NumPydata~10 mins

Partial sorting with np.partition() in NumPy - Interactive Code Practice

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

Complete the code to partially sort the array so the smallest 3 elements are in the first 3 positions.

NumPy
import numpy as np
arr = np.array([7, 2, 5, 3, 9, 1])
result = np.partition(arr, [1])
print(result)
Drag options to blanks, or click blank then click option'
A3
B2
C4
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using an index larger than the array length causes an error.
Confusing the partition index with sorting the whole array.
2fill in blank
medium

Complete the code to get the 2 smallest elements using np.partition.

NumPy
import numpy as np
arr = np.array([10, 4, 6, 2, 8])
partitioned = np.partition(arr, [1])
smallest_two = partitioned[:2]
print(smallest_two)
Drag options to blanks, or click blank then click option'
A2
B1
C3
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 2 as partition index returns 3 smallest elements, not 2.
Using 0 returns only the smallest element.
3fill in blank
hard

Fix the error in the code to correctly partition the array to get the 4 smallest elements.

NumPy
import numpy as np
arr = np.array([9, 1, 7, 3, 5])
result = np.partition(arr, [1])
print(result[:4])
Drag options to blanks, or click blank then click option'
A3
B4
C2
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using 4 as partition index causes an error because index is out of bounds.
Using 5 is invalid since array length is 5 and max index is 4.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths as values, but only for words longer than 4 characters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog', 'elephant']
lengths = { [1] : [2] for word in words if len(word) > 4 }
print(lengths)
Drag options to blanks, or click blank then click option'
Aword
Blen(word)
Cword.upper()
Dlen
Attempts:
3 left
💡 Hint
Common Mistakes
Using len as a value instead of len(word).
Using word.upper() as key changes the original word.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys and their lengths as values, but only for words shorter than 6 characters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog', 'elephant']
result = { [1] : [2] for word in words if len(word) [3] 5 }
print(result)
Drag options to blanks, or click blank then click option'
Aword.upper()
Blen(word)
C<=
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<=' in the condition.
Using 'word' instead of 'word.upper()' as keys.