Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find the middle number in python

Tags:

python

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?

like image 289
damon Avatar asked Apr 02 '12 15:04

damon


People also ask

How do you find the middle of a number in Python?

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.

What is the middle number in an ordered 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.


3 Answers

Put them in a list, sort them, pick the middle one.

like image 192
Sven Marnach Avatar answered Nov 15 '22 06:11

Sven Marnach


>>> x = [1,3,2]
>>> sorted(x)[len(x) // 2]
2
like image 30
jamylak Avatar answered Nov 15 '22 07:11

jamylak


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
like image 39
Zaur Nasibov Avatar answered Nov 15 '22 08:11

Zaur Nasibov