Skip to content

Comparisons and conditional expressions [ref]

Problem

  • Test whether 5 is in the half-open interval from 0 to 10.
  • Test whether 3 <= 3 < 5.
  • Return -1 for x = -4, otherwise 1, using a conditional expression.
  • Test whether exactly one of -2 and 3 is negative.
  • Clamp 15 to the inclusive interval from 0 through 10.
  • Compare "10" and "26" lexicographically with "15".

Python solution

0 <= 5 < 10  # True

3 <= 3 < 5  # True

x = -4
-1 if x < 0 else 1  # -1

a, b = -2, 3
(a < 0) != (b < 0)  # True

max(0, min(15, 10))  # 10

"10" <= "15" <= "26"  # True; equal-length digit strings