The snippet library.
Small, practical examples. Search by task or narrow things down below.
Calculate the number of required pages
Python: Use integer arithmetic to round a nonnegative count up to a positive page size.
Python✓ Tested
Calculate with exact rational values
Python: Use Fraction for exact ratios rather than binary floating-point approximations.
Python✓ Tested
Clamp a numeric value between bounds
Python: Combine min and max for a closed interval when lower is no greater than upper.
Python✓ Tested
Compare floating-point calculations with tolerance
Python: Use isclose instead of exact equality for results affected by floating-point rounding.
Python✓ Tested
Find common factors and multiples
Python: Use the integer gcd and lcm helpers to avoid floating-point calculations.
Python✓ Tested
Find the mean and median of readings
Python: Use statistics helpers to distinguish an arithmetic mean from a middle value.
Python✓ Tested
Insert a value while preserving sorted order
Python: Use insort on an already sorted list; insertion still shifts later list elements.
Python✓ Tested
Reject NaN and infinite numeric inputs
Python: Use isfinite before computations that require an ordinary finite float.
Python✓ Tested
Round decimal amounts explicitly
Python: Build Decimal values from strings and choose a rounding rule explicitly.
Python✓ Tested
Select the largest values without sorting everything
Python: Use heapq.nlargest when only a small prefix of the ranking is required.
Python✓ Tested