075. Standard Library (Math, Random, Datetime)
Python's batteries-included standard library saves time
075. Standard Library (Math, Random, Datetime)
He needs three small utilities for the RAM manager: generate a random session token, calculate how many hours until the next scheduled maintenance window, and clamp RAM percentage to the valid 0–100 range.
Before reaching for pip install:
import math
import random
from datetime import datetime, timedelta
# Random session token for the alert webhook
def make_token(length=16):
chars = "abcdefghijklmnopqrstuvwxyz0123456789"
return "".join(random.choices(chars, k=length))
# Hours until next scheduled maintenance
def hours_until(target_dt):
delta = target_dt - datetime.now()
return max(0, delta.seconds // 3600 + delta.days * 24)
# Keep RAM percent in a valid range
def clamp(value, lo, hi):
return max(lo, min(value, hi))All three utilities come from the standard library — no pip install, no dependency management, no version conflicts.
💡 The Python standard library is large. Before writing any utility, search docs.python.org/3/library.
Learning objectives
- Use random module for random selection with and without replacement
- Work with datetime.date for date arithmetic
- Apply math functions for numerical operations
Key concepts
- standard library
- random module
- datetime module
- math module
Try it
Concept detail
Python’s standard library: “batteries included” — no pip install needed.
math: math.sqrt(x), math.pi, math.floor(x), math.ceil(x) math.log(x, base), math.gcd(a, b), math.isclose(a, b)
random: random.random() → float in [0, 1) random.randint(a, b) → int in [a, b] inclusive random.choice(seq) → one random element random.choices(seq, k=n) → n elements WITH replacement (allows repeats) random.sample(seq, k) → k elements WITHOUT replacement (no repeats, crashes if k > len) random.shuffle(lst) → shuffle list in-place
datetime: date.today() → today’s date datetime.now() → current date + time timedelta(days=n) → a duration (date2 - date1).days → number of days between two dates .strftime(“%Y-%m-%d”) → format as string
Other essentials (no install needed): collections.Counter, collections.defaultdict itertools.chain, itertools.product json.dumps / json.loads re.findall / re.sub os.path.join / os.listdir
Finding modules: docs.python.org/3/library or help() in the REPL.
Solution
import math
import random
from datetime import date
CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
def random_password(length):
return "".join(random.choices(CHARS, k=length))
def days_until(year, month, day):
target = date(year, month, day)
today = date.today()
return (target - today).days
def clamp(value, lo, hi):
return max(lo, min(value, hi))Tests
def test_random_password_length():
pw = random_password(12)
assert len(pw) == 12
def test_random_password_long():
# random.sample crashes for length > 62 (len(CHARS)), random.choices works
pw = random_password(100)
assert len(pw) == 100
def test_random_password_chars():
pw = random_password(20)
assert all(c in CHARS for c in pw)
def test_clamp_within():
assert clamp(5, 0, 10) == 5
def test_clamp_below():
assert clamp(-5, 0, 10) == 0
def test_clamp_above():
# BUG: broken code returns max(0, 15) = 15, not 10
assert clamp(15, 0, 10) == 10
def test_days_until_type():
from datetime import date
result = days_until(2030, 1, 1)
assert isinstance(result, int)
def test_days_until_positive():
result = days_until(2030, 1, 1)
assert result > 0