JuniorCodeCommonNot answered yet
Return the median of three integers without sorting
Implement median3(a, b, c) returning the middle value of three integers.
Requirements:
- Use comparisons, not
sorted(...). - Handle the case where some or all values are equal.
def median3(a, b, c):
# your code here
Write the implementation.
The median is the value not equal to both the max and the min. A clean trick: a + b + c - max(a, b, c) - min(a, b, c). With comparisons, the median is the one that lies between the other two, e.g. if (a <= b <= c) or (c <= b <= a): return b, and so on. Equal values are handled because <= keeps ties valid.
- ✗Returning
bunconditionally, ignoring that any argument can be the median - ✗Forgetting equal-value cases like
a == b == cor two equal inputs - ✗Confusing the median (middle value) with the mean (average)
- →Why does
sum - max - mincorrectly yield the median of exactly three values? - →Which test inputs would catch a solution that mishandles equal values?
Contents
Task
Implement median3: return the middle value of three integers using comparisons, handling equal values.
Solution
def median3(a, b, c):
return a + b + c - max(a, b, c) - min(a, b, c)
# Equivalent with comparisons:
def median3_cmp(a, b, c):
if (a <= b <= c) or (c <= b <= a):
return b
if (b <= a <= c) or (c <= a <= b):
return a
return c
Key points
- Sum minus max minus min leaves exactly the middle value — works with ties too.
- With comparisons,
<=keeps correctness when values are equal (a == b == c). - The median is the middle value, not the arithmetic mean.
Contents