Finding “median-of-three” with two comparisons – Python implementation

def find_median(a,b,c):
    # (A-B)*(C-A) >= 0
    if (a – b)*(c-a) >= 0:
        return a
        #A
    # (B – A)*(C-B) >=0
    elif (b – a) * (c – b) >=0:
        return b
        #B
    else:
        #C
        return c
a = 1
b = 3
c = 7
print find(a,b,c)
a = 1
b = 6
c = 2
print find(a,b,c)
Advertisements

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: