0
0
NumPydata~10 mins

Random choice from array 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 select a random element from the array using NumPy.

NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
random_element = np.random.[1](arr)
print(random_element)
Drag options to blanks, or click blank then click option'
Ashuffle
Bchoice
Crandint
Drandom
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.random.randint which returns a random integer, not an element from the array.
Using np.random.shuffle which shuffles the array instead of selecting one element.
2fill in blank
medium

Complete the code to select 3 random elements from the array with replacement.

NumPy
import numpy as np
arr = np.array([5, 10, 15, 20, 25])
sample = np.random.choice(arr, size=[1], replace=True)
print(sample)
Drag options to blanks, or click blank then click option'
A1
B5
C3
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Setting size to 1 or 5 which does not match the requirement.
Forgetting to set replace=True when sampling with replacement.
3fill in blank
hard

Fix the error in the code to select 2 unique random elements from the array.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
sample = np.random.choice(arr, size=[1], replace=False)
print(sample)
Drag options to blanks, or click blank then click option'
A2
B3
C4
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using replace=True which allows duplicates.
Setting size to 1 or more than 2 which does not match the requirement.
4fill in blank
hard

Fill both blanks to create a dictionary with elements as keys and their squares as values for elements greater than 3.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
squares = {x: x[1]2 for x in arr if x [2] 3}
print(squares)
Drag options to blanks, or click blank then click option'
A**
B%
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using % instead of ** for power.
Using < instead of > for filtering.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase keys and values greater than 10.

NumPy
data = {'a': 5, 'b': 15, 'c': 20}
result = [1]: [2] for [3], [2] in data.items() if [2] > 10
print(result)
Drag options to blanks, or click blank then click option'
Ak.upper()
Bv
Ck
Ditem
Attempts:
3 left
💡 Hint
Common Mistakes
Using item as loop variable instead of k.
Not converting keys to uppercase.
Using wrong variable names for keys or values.