Skip to the content.

Math and numbers: Python snippets

Part of 30 Seconds of Python. Source: snippets/numeric.py. Every example below is run as a test.

clamp

Limit n to the range [low, high].

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

in_range

True if start <= n < end (with one bound, the range is 0..start).

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

average

Arithmetic mean of the arguments.

def average(*nums):
    return sum(nums) / len(nums)
>>> average(1, 2, 3, 4)
2.5

median

Middle value (the mean of the two middle values for even counts).

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

round_to

Round to the nearest multiple of step.

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

percent

Percentage of part in whole, rounded.

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

lerp

Linear interpolation between a and b (t=0 gives a, t=1 gives b).

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

is_prime

Primality test by trial division up to sqrt(n).

def is_prime(n):
    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))
>>> [x for x in range(20) if is_prime(x)]
[2, 3, 5, 7, 11, 13, 17, 19]

primes_up_to

Sieve of Eratosthenes: every prime <= limit.

def primes_up_to(limit):
    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]
>>> primes_up_to(30)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

fibonacci

First n Fibonacci numbers.

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

digits

Decimal digits of an integer.

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

lcm_all

Least common multiple of several integers (math.lcm, Python 3.9+).

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

gcd_all

Greatest common divisor of several integers.

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

is_close

Float comparison that survives rounding error.

def is_close(a, b, rel=1e-9, abs_tol=0.0):
    return math.isclose(a, b, rel_tol=rel, abs_tol=abs_tol)
>>> 0.1 + 0.2 == 0.3, is_close(0.1 + 0.2, 0.3)
(False, True)

to_base

Integer to a string in base 2..36.

def to_base(n, base):
    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))
>>> to_base(255, 16), to_base(5, 2), to_base(-35, 36)
('ff', '101', '-z')