abs, pow, round, divmod
Numeric built-ins that come up in math-flavored problems. Three-argument pow does fast modular exponentiation (and modular inverse), divmod returns quotient and remainder at once, and round uses banker's rounding.
Syntax
abs(-5) # -> 5
pow(2, 10) # -> 1024, same as 2 ** 10
divmod(17, 5) # -> (3, 2)
round(3.14159, 2) # -> 3.14
Modular exponentiation and inverse
MOD = 10**9 + 7
pow(2, 100, MOD) # -> 976371285, O(log e), never builds the huge number
pow(3, -1, 7) # -> 5, modular inverse: 3 * 5 % 7 == 1 (3.8+)
pow(5, MOD - 2, MOD) # inverse via Fermat when MOD is prime
round: banker's rounding
round(0.5) # -> 0, ties go to the even neighbor
round(1.5) # -> 2
round(2.5) # -> 2, not 3
round(2.675, 2) # -> 2.67, float representation error
import math
math.floor(2.5 + 0.5) # -> 3, round half up for non-negatives
divmod and negative numbers
q, r = divmod(17, 5) # -> 3, 2
divmod(-7, 2) # -> (-4, 1), floors toward -inf
-7 // 2, -7 % 2 # -> (-4, 1), same as divmod
int(-7 / 2) # -> -3, truncates toward 0 (C-style)
row, col = divmod(7, 3) # flat index -> (2, 1) in a 3-wide grid
abs
abs(-3.5) # -> 3.5
abs(3 - 4j) # -> 5.0, magnitude of a complex number
x1, y1, x2, y2 = 0, 0, 3, -4
abs(x1 - x2) + abs(y1 - y2) # -> 7, Manhattan distance