Created
September 23, 2017 22:16
-
-
Save asifm/a703c4cacd72296644f4957da1e31a44 to your computer and use it in GitHub Desktop.
Find median of three numbers without using a list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The principle is to exhaustively compare all three numbers, so that we can know | |
# the order of the three numbers. We can do this with 3 levels of if statements. | |
# At first level we compare two of the three numbers (here a and b) and then | |
# at the next level we compare another pair (such as b and c or a and c). And then | |
# at the last level we compare the last remaining pair, if necessary. This way | |
# we exhaust all possibilities. | |
def median(a, b, c): | |
# First compare the first two numbers a and b. | |
# For a and b, there are only two possibilities. Either a > b or b >= a | |
# (We don't need to check a == b, because if they're equal it doesn't matter which one we choose) | |
# If a is greater than b then execute Block 1. Else execute Block 2 | |
# Block 1 | |
if a > b: | |
# If a is greater than b, then let's first compare a and c and then compare b and c | |
# There are only two possibilities. Either a > c or c >= a | |
if a > c: | |
if b > c: | |
# If a > b, a > c, and b > c, we can infer a > b > c. So b is median | |
return b | |
else: | |
# This "else" covers the condition c >= b | |
# If a > b, a > c, c >= b, we can infer a > c >= b. So c is median | |
return c | |
else: | |
# If a is not greater than c, then c >= a. | |
# This "else" covers the conditions a > b and c >= a. We don't need to check b and c here | |
# Because we can already infer c >= a > b. So median is a | |
return a | |
# Possibility 2: If a is not greater than b, then b must be greater than or equal to a. | |
# Both of these situations are covered in the "else" block below. | |
# Because "else" covers all all remaining conditions | |
# So we have covered all possibilities as far as the first two numbers a and b are concerned | |
# We can be sure either Block 1 or Block 2 will run. | |
# Block 2 | |
# Follow the same logic as above. | |
else: | |
if b > c: | |
if a > c: | |
# We now know b >= a, b > c, and a > c. So b >= a > c. So a is median | |
return a | |
else: | |
return c | |
else: | |
return b | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment