0
0
NumPydata~10 mins

Logical operations (and, or, not) 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 create a boolean array where values are True if elements in array 'a' are greater than 5.

NumPy
import numpy as np

a = np.array([3, 7, 2, 9, 5])
result = a [1] 5
Drag options to blanks, or click blank then click option'
A>
B<
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' which selects smaller values.
Using '==' which checks for equality, not greater than.
2fill in blank
medium

Complete the code to find elements in 'a' that are greater than 2 and less than 8 using logical operations.

NumPy
import numpy as np

a = np.array([1, 3, 5, 7, 9])
result = (a > 2) [1] (a < 8)
Drag options to blanks, or click blank then click option'
Aor
Band
C|
D&
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'and' which does not work element-wise on numpy arrays.
Using '|' which is for OR operation.
3fill in blank
hard

Fix the error in the code to correctly apply logical OR between two conditions on numpy arrays.

NumPy
import numpy as np

a = np.array([1, 4, 6])
b = np.array([3, 5, 2])
result = (a > 3) [1] (b < 5)
Drag options to blanks, or click blank then click option'
Aor
Band
C|
D&
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'or' which causes a ValueError with numpy arrays.
Using '&' which is for AND, not OR.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps words to True if their length is greater than 3 and the word contains letter 'a'.

NumPy
words = ['cat', 'dog', 'apple', 'bat']
result = {word: (len(word) [1] 3) [2] ('a' in word) for word in words}
Drag options to blanks, or click blank then click option'
A>
Band
C&
D|
Attempts:
3 left
💡 Hint
Common Mistakes
Using '&' which is a bitwise operator and not suitable here.
Using '|' which means OR, not AND.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps words to True if the word starts with 'b', does not contain 'e', and has length less than 5.

NumPy
words = ['bat', 'bee', 'ball', 'cat']
result = {word: (word[1]'b') [2] ([3]('e' in word)) and len(word) < 5 for word in words}
Drag options to blanks, or click blank then click option'
A.startswith(
Band
Cnot
Dor
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'or' instead of 'and' which changes logic.
Omitting 'not' which reverses the condition.