Skip to content

Mathematical standard-library helpers [ref]

Problem

  • Choose 2 items from 4 using math.comb.
  • Find the greatest common divisor of 18 and 24.
  • Find integer square roots of 15 and 16.
  • Test whether 49 is a perfect square.
  • Reduce direction (6, 9) to its smallest integer pair.

Python solution

import math

math.comb(4, 2)  # 6

math.gcd(18, 24)  # 6

(math.isqrt(15), math.isqrt(16))  # (3, 4)

root = math.isqrt(49)
root * root == 49  # True

dy, dx = 6, 9
g = math.gcd(abs(dy), abs(dx))
(dy // g, dx // g)  # (2, 3)