"""Math and number snippets."""
import math
from statistics import median as _median


def clamp(n, low, high):
    """Limit ``n`` to the range [low, high].

    >>> clamp(15, 0, 10), clamp(-3, 0, 10), clamp(5, 0, 10)
    (10, 0, 5)
    """
    return max(low, min(n, high))


def in_range(n, start, end=None):
    """True if start <= n < end (with one bound, the range is 0..start).

    >>> in_range(3, 2, 5), in_range(3, 4), in_range(5, 2, 5)
    (True, True, False)
    """
    if end is None:
        start, end = 0, start
    return min(start, end) <= n < max(start, end)


def average(*nums):
    """Arithmetic mean of the arguments.

    >>> average(1, 2, 3, 4)
    2.5
    """
    return sum(nums) / len(nums)


def median(nums):
    """Middle value (the mean of the two middle values for even counts).

    >>> median([3, 1, 4, 1, 5]), median([1, 2, 3, 4])
    (3, 2.5)
    """
    return _median(nums)


def round_to(n, step):
    """Round to the nearest multiple of ``step``.

    >>> round_to(17, 5), round_to(0.37, 0.25)
    (15, 0.25)
    """
    return round(n / step) * step


def percent(part, whole, digits=1):
    """Percentage of ``part`` in ``whole``, rounded.

    >>> percent(1, 3)
    33.3
    """
    return round(100 * part / whole, digits) if whole else 0.0


def lerp(a, b, t):
    """Linear interpolation between a and b (t=0 gives a, t=1 gives b).

    >>> lerp(10, 20, 0.25)
    12.5
    """
    return a + (b - a) * t


def is_prime(n):
    """Primality test by trial division up to sqrt(n).

    >>> [x for x in range(20) if is_prime(x)]
    [2, 3, 5, 7, 11, 13, 17, 19]
    """
    if n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    return all(n % d for d in range(3, math.isqrt(n) + 1, 2))


def primes_up_to(limit):
    """Sieve of Eratosthenes: every prime <= limit.

    >>> primes_up_to(30)
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    """
    if limit < 2:
        return []
    sieve = bytearray([1]) * (limit + 1)
    sieve[0] = sieve[1] = 0
    for i in range(2, math.isqrt(limit) + 1):
        if sieve[i]:
            sieve[i * i::i] = bytes(len(range(i * i, limit + 1, i)))
    return [i for i, flag in enumerate(sieve) if flag]


def fibonacci(n):
    """First ``n`` Fibonacci numbers.

    >>> fibonacci(10)
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
    """
    out, a, b = [], 0, 1
    for _ in range(n):
        out.append(a)
        a, b = b, a + b
    return out


def digits(n):
    """Decimal digits of an integer.

    >>> digits(-4096)
    [4, 0, 9, 6]
    """
    return [int(c) for c in str(abs(n))]


def lcm_all(*nums):
    """Least common multiple of several integers (math.lcm, Python 3.9+).

    >>> lcm_all(4, 6, 10)
    60
    """
    return math.lcm(*nums)


def gcd_all(*nums):
    """Greatest common divisor of several integers.

    >>> gcd_all(12, 18, 30)
    6
    """
    return math.gcd(*nums)


def is_close(a, b, rel=1e-9, abs_tol=0.0):
    """Float comparison that survives rounding error.

    >>> 0.1 + 0.2 == 0.3, is_close(0.1 + 0.2, 0.3)
    (False, True)
    """
    return math.isclose(a, b, rel_tol=rel, abs_tol=abs_tol)


def to_base(n, base):
    """Integer to a string in base 2..36.

    >>> to_base(255, 16), to_base(5, 2), to_base(-35, 36)
    ('ff', '101', '-z')
    """
    if not 2 <= base <= 36:
        raise ValueError('base must be 2..36')
    chars = '0123456789abcdefghijklmnopqrstuvwxyz'
    if n == 0:
        return '0'
    sign, n = ('-', -n) if n < 0 else ('', n)
    out = []
    while n:
        n, r = divmod(n, base)
        out.append(chars[r])
    return sign + ''.join(reversed(out))
