Unit conversion
A duration must be decomposed into larger and smaller units.
Python · Function
divmod() returns a pair containing the quotient and remainder for two non-complex numbers. For integers, it is equivalent to (a // b, a % b), while floating-point inputs have documented rounding nuances.
divmod(a, b) performs division and returns both results as a two-item tuple: the quotient from integer division and the remainder. For integers, it is equivalent to (a // b, a % b); for floating-point operands, the quotient generally follows floor division but can differ by one because of rounding.
divmod(a, b, /)| Name | Type | Description |
|---|---|---|
a | number | The dividend, a non-complex number to divide. |
b | number | The divisor, a non-complex number used for integer division and the remainder. |
A pair of numbers containing the quotient and remainder from integer division.
total_seconds = 3671
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
print(hours, minutes, seconds) # 1 1 11The first call splits seconds into whole minutes and leftover seconds; the second splits minutes into hours and leftover minutes.
A duration must be decomposed into larger and smaller units.
A sequence is processed in fixed-size groups and both the group index and position are needed.
A cyclic position must be represented as a cycle count plus an offset.
divmod() return for integers?For integer operands, divmod(a, b) returns exactly the same pair as (a // b, a % b). It packages the quotient and remainder together, which is useful when both values are needed.
Follow-up: How does this differ for floats? The returned pair is (q, a % b); q is usually math.floor(a / b), but floating-point behavior can make it one less.
divmod() accept?The function returns a pair containing the quotient and remainder from integer division. With operands of mixed types, Python applies the normal rules for binary arithmetic operators.
Follow-up: What restriction applies regardless of numeric type? The inputs must be non-complex numbers.
divmod() behave with floating-point numbers?For floating-point inputs, the quotient is usually the floor of the mathematical division, while the remainder is computed as a % b. The documentation notes that floating-point rounding can make the quotient one less than the usual floor result.
Follow-up: What relationship should still approximately hold? q * b + a % b should be very close to a.
//%math.floor