"""
Solution: right numbers, wrong answers. Lab 02's second half (02_hdr_histogram.py Exercise 2,
05_fanout.py, 06_aa_noise.py).
"""
import math
import statistics


def percentile(xs, q):
    """The q-th percentile (0-100), nearest-rank (numpy's inverted_cdf)."""
    s = sorted(xs)
    rank = max(1, math.ceil(q / 100 * len(s)))
    return s[rank - 1]


def mean_of_percentiles(windows, q):
    """The average of each window's q-th percentile: what not to do."""
    return sum(percentile(w, q) for w in windows) / len(windows)


def tally(xs, edges):
    """Counts per range; edges are ascending upper bounds."""
    counts = [0] * len(edges)
    for x in xs:
        for i, e in enumerate(edges):
            if x <= e:
                counts[i] += 1
                break
    return counts


def merge(a, b):
    """Two tallies with the same edges, added range by range."""
    return [x + y for x, y in zip(a, b)]


def percentile_from_tally(counts, edges, q):
    """The upper bound of the range that holds the nearest-rank q-th percentile."""
    rank = max(1, math.ceil(q / 100 * sum(counts)))
    seen = 0
    for c, e in zip(counts, edges):
        seen += c
        if seen >= rank:
            return e
    return edges[-1]


def p_any_slow(n, p_slow=0.01):
    """1 - (1 - p)^n: at least one of n independent calls is slow."""
    return 1 - (1 - p_slow) ** n


def share_with_slow(pages, slow_line):
    """Share of pages whose slowest call is over the line."""
    return sum(1 for calls in pages if max(calls) > slow_line) / len(pages)


def single_percentile_for_slowest(n, q=99):
    """P(max <= t) = F(t)^n, so the slowest's q-th percentile is one call's (q/100)^(1/n) quantile."""
    return 100 * (q / 100) ** (1 / n)


def spread(values):
    """(max - min) / median over identical runs."""
    return (max(values) - min(values)) / statistics.median(values)


def beats_noise(after, aa_values):
    """Outside the A/A range?"""
    return after < min(aa_values) or after > max(aa_values)
