0
0
NumPydata~10 mins

np.count_nonzero() for counting 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 count non-zero elements in the array.

NumPy
import numpy as np
arr = np.array([0, 1, 2, 0, 3])
count = np.[1](arr)
print(count)
Drag options to blanks, or click blank then click option'
Acount_nonzero
Bsum
Cnonzero
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using np.sum() counts the sum of elements, not the count of non-zero elements.
Using np.nonzero() returns indices, not the count.
2fill in blank
medium

Complete the code to count non-zero elements along axis 0.

NumPy
import numpy as np
arr = np.array([[0, 1, 2], [3, 0, 0]])
count = np.count_nonzero(arr, axis=[1])
print(count)
Drag options to blanks, or click blank then click option'
A1
B-1
C2
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using axis=1 counts across rows, not columns.
Using negative axis values may cause confusion.
3fill in blank
hard

Fix the error in the code to correctly count non-zero elements in a boolean array.

NumPy
import numpy as np
arr = np.array([True, False, True, False])
count = np.count_nonzero([1])
print(count)
Drag options to blanks, or click blank then click option'
Aarr.nonzero()
Barr
Cnp.sum(arr)
Darr.sum()
Attempts:
3 left
💡 Hint
Common Mistakes
Passing arr.sum() returns a number, not an array, causing errors.
Passing arr.nonzero() returns indices, not suitable here.
4fill in blank
hard

Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.

NumPy
words = ['cat', 'house', 'dog', 'elephant']
lengths = {word: [1] for word in words if len(word) [2] 3}
print(lengths)
Drag options to blanks, or click blank then click option'
Alen(word)
Bword
C>
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using word instead of len(word) stores the word, not its length.
Using '<=' includes shorter words, not longer.
5fill in blank
hard

Fill all three blanks to create a dictionary of uppercase words and their counts if count is greater than 1.

NumPy
data = {'apple': 2, 'banana': 1, 'cherry': 3}
result = { [1]: [2] for word in data if data[word] [3] 1 }
print(result)
Drag options to blanks, or click blank then click option'
Aword
Bdata[word]
C>
Dword.upper()
Attempts:
3 left
💡 Hint
Common Mistakes
Using word instead of word.upper() keeps keys lowercase.
Using '<' or '<=' includes unwanted counts.