Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Find Median Value

Find the median of three values without sorting a list. A Python exercise on two possible orderings, compound conditions, and handling equal middle values.

IntermediatePhase 1 - Level 4: Logical Operators & Compound StatementsExample 3 of 10
find-median-value.py
1# Take three numbers
2a = float(input("Enter first number: "))
3b = float(input("Enter second number: "))
4c = float(input("Enter third number: "))
5
6# Find median
7if (a >= b and a <= c) or (a <= b and a >= c):
8 median = a
9elif (b >= a and b <= c) or (b <= a and b >= c):
10 median = b
11else:
12 median = c
13
14print(f"Median: {median}")

Output

Enter first number: 10
Enter second number: 5
Enter third number: 15
Median: 10.0

In this one

  • Define a median
  • Check both possible orderings
  • Preserve equal values

How it works

  1. 1

    Read three floats.

  2. 2

    Test whether a lies between the others, then b.

  3. 3

    Otherwise select c and print median.

Edge cases

What is the median of 2, 2, 9?

What is the median of 2, 2, 9?

2; duplicates still occupy positions in the ordered data.

Is this the arithmetic mean?

Is this the arithmetic mean?

No. It selects the middle value rather than adding and dividing.

What's going on

The median of three values is the middle one when ordered. a qualifies if it lies between b and c in either direction, which explains the two groups joined by or.

If a is not between them, the next test tries b. Otherwise c must be the middle value. Inclusive comparisons keep equal values valid. The sample 10, 5, 15 chooses 10.0, not the average of the three.

What is the median of 2, 2, 9? 2; duplicates still occupy positions in the ordered data.

Is this the arithmetic mean? No. It selects the middle value rather than adding and dividing.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why check two arrangements for a?

Pick an answer to check it.

Question 2

What is the median of 2, 2, 9?

Pick an answer to check it.

Questions people ask

What is the median of 2, 2, 9?

2; duplicates still occupy positions in the ordered data.

Is this the arithmetic mean?

No. It selects the middle value rather than adding and dividing.

Why check two arrangements for a?

Either b or c may be the smaller neighbor.