An Elegant Way To Find Out Median Of Three Numbers In Python
There are multiple ways of doing this.
The first one is the comparison way -
>>> def median3(a,b,c): ... if a<b: ... if c<a: ... return a ... elif b<c: ... return b ... else: ... return c ... else: ... if a<c: ... return a ... elif c<b: ... return b ... else: ... return c ... >>> median3(1,5,2) 2 >>> median3(3,5,2) 3 >>> median3(3,5,7) 5 >>> median3(7,5,2) 5 >>> median3(7,5,1) 5 >>> median3(2,5,1) 2
this takes at least two comparisons and at most three to compute.
Another elegant way to do this might be to sort the three numbers and return the middle one.
Like this:
>>> def median3(a,b,c): ... return sorted([a,b,c])[1] ... >>> median3(1,5,2) 2 >>> median3(3,5,2) 3 >>> median3(3,5,7) 5 >>> median3(7,5,6) 6







