0
0
NumPydata~20 mins

Histogram computation with np.histogram() in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Histogram Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.histogram() with bins=6
What is the output of the following code snippet?
NumPy
import numpy as np

arr = np.array([1, 2, 2, 3, 4, 5, 5, 5, 6])
hist, bins = np.histogram(arr, bins=6)
print(hist, bins)
A[1 2 1 0 3 2] [1. 2. 3. 4. 5. 6. ]
B[1 2 1 1 3 1] [1. 2. 3. 4. 5. 6. 7. ]
C[1 2 1 1 3 2] [1. 1.83333333 2.66666667 3.5 4.33333333 5.16666667 6. ]
D[1 2 1 1 3 2] [1. 2. 3. 4. 5. 6. 7. ]
Attempts:
2 left
💡 Hint
Check how np.histogram divides the range into equal-width bins when bins=6.
data_output
intermediate
2:00remaining
Number of bins and counts with custom bins
Given the array and bins, what is the output counts array from np.histogram?
NumPy
import numpy as np

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
bins = [0, 3, 6, 9]
hist, _ = np.histogram(arr, bins=bins)
print(hist)
A[3 4 3]
B[3 3 4]
C[4 3 3]
D[3 3 3]
Attempts:
2 left
💡 Hint
Count how many numbers fall into each bin range: [0-3), [3-6), [6-9).
🔧 Debug
advanced
2:00remaining
Identify the error in np.histogram bin specification
What error does the following code raise?
NumPy
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
bins = [5, 4, 3, 2, 1]
hist, edges = np.histogram(arr, bins=bins)
AValueError: bins must increase monotonically.
BTypeError: bins must be an integer or sequence.
CIndexError: list index out of range.
DNo error, runs successfully.
Attempts:
2 left
💡 Hint
Bins must be sorted in ascending order.
visualization
advanced
2:00remaining
Histogram bin edges with uneven bin widths
What are the bin edges and counts for this histogram?
NumPy
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
bins = [1, 3, 6, 10]
hist, edges = np.histogram(arr, bins=bins)
print(hist, edges)
A[2 3 4] [ 1 3 6 10]
B[2 4 3] [ 1 3 6 10]
C[3 3 3] [ 1 3 6 10]
D[2 3 3] [ 1 3 6 10]
Attempts:
2 left
💡 Hint
Count how many values fall into each bin: [1-3), [3-6), [6-10).
🚀 Application
expert
3:00remaining
Calculate histogram and cumulative counts
Given the array, which option correctly computes the histogram counts and cumulative counts using np.histogram?
NumPy
import numpy as np

arr = np.array([2, 4, 4, 4, 5, 5, 7, 9])
bins = [0, 3, 6, 9, 12]
hist, edges = np.histogram(arr, bins=bins)
cum_counts = np.cumsum(hist)
print(hist, cum_counts)
A[1 4 2 1] [1 5 7 8]
B[1 5 1 1] [1 6 7 8]
C[2 4 1 1] [2 6 7 8]
D[1 5 2 0] [1 6 8 8]
Attempts:
2 left
💡 Hint
Count values in each bin and then sum counts cumulatively.