Floor division, modulo, and `divmod` [ref]
Problem
- Compute the quotient and remainder of
32 divided by 10.
- Extract the last digit of
123 and remove it.
- Check whether
18 is divisible by 3.
- Compare floor division and truncation toward zero for
-7 divided by 3.
- Obtain both results for
17 divided by 5 in one call.
- Normalize rotation
9 for a list of length 4.
Python solution
32 // 10 # 3
32 % 10 # 2
n = 123
digit = n % 10
n //= 10
(digit, n) # (3, 12)
18 % 3 == 0 # True
-7 // 3 # -3
int(-7 / 3) # -2
divmod(17, 5) # (3, 2)
k, n = 9, 4
k %= n
k # 1; n must be nonzero
Links