Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Edge case: integer division and modulo with negative operands in Python.

Edge case: integer division and modulo with negative operands in Python.
print(-7 // 2, -7 % 2, int(-7 / 2))
What is printed?
  1. A. -3 -1 -3
  2. B. -4 -1 -4
  3. C. -3 1 -4
  4. D. -4 1 -3

Correct answer: D. -4 1 -3

Python's // floors toward −∞, so −7 // 2 = −4, and % takes the sign of the divisor, so −7 % 2 = 1 (−4 × 2 + 1 = −7). int(−3.5) truncates toward zero, giving −3. C, C++ and Java truncate: −7 / 2 = −3 and −7 % 2 = −1.

More Coding Interview Problems questions

Exams that ask this topic