Given 3 numbers, I need to find which number lies between the two others.
ie,given 3,5,2 I need 3 to be returned.
I tried to implement this by going thru all three and using if else conditions to check if each is between the other two.But this seems a naive way to do this.Is there a better way?
With the Python statistics module, you can find the median, or middle value, of a data set. The Python median() function allows you to calculate the median of any data set without first sorting the list.
Median is the middle number in a sorted list of numbers. To determine the median value in a sequence of numbers, the numbers must first be sorted, or arranged, in value order from lowest to highest or highest to lowest.
Put them in a list, sort them, pick the middle one.
>>> x = [1,3,2]
>>> sorted(x)[len(x) // 2]
2
The fastest obvious way for three numbers
def mean3(a, b, c):
if a <= b <= c or c <= b <= a:
return b
elif b <= a <= c or c <= a <= b:
return a
else:
return c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With