791. Estimate probabilities from a sample stream and test it for uniformity
Say a sampler is supposed to pick one of k buckets uniformly at random, for example a load balancer or a data shuffler. You get a stream of its outputs and want to know if it looks fair.
Write check_uniform(stream, k, critical). stream is a list of ints. Values outside 0 to k - 1 are invalid and ignored. Let n be the number of valid values. Return a dict with:
'probs': the estimated probability of each bucket (count / n), rounded to 4 decimals. 'chi2': the chi-square statistic, the sum over buckets of (count - n / k) squared divided by n / k, rounded to 4 decimals. 'uniform': True if chi2 is at most critical. If n is 0, return probs of all 0.0, chi2 0.0 and uniform True.
def check_uniform(stream, k, critical)Example 1
Input: check_uniform([0, 1, 1, 2, 2, 2], 3, 5.991)
Output: {'probs': [0.1667, 0.3333, 0.5], 'chi2': 1.0, 'uniform': True}
Example 2
Input: stream = [0, 1, 2, 3] * 25, k = 4, critical = 7.815
Output: {'probs': [0.25, 0.25, 0.25, 0.25], 'chi2': 0.0, 'uniform': True}
Example 3
Input: stream = [0] * 90 + [1] * 10, k = 2, critical = 3.841
Output: {'probs': [0.9, 0.1], 'chi2': 64.0, 'uniform': False}
Constraints
- k up to 1,000.
- Stream length up to 1,000,000.
Hint 1
Count, then divide by the number of valid samples.
Hint 2
Expected count per bucket is n / k.
Hint 3
Handle n = 0 before dividing.
Common mistakes
- Dividing by the full stream length including invalid values.
- Using k instead of k - 1 degrees of freedom when picking the critical value.
- Forgetting buckets that never appear, which have count 0 but still add to chi2.
Understand the idea
Goodness of fit: compare observed bucket counts with the counts a uniform sampler would give.