How to find average in python

Given 3 numbers, I need to find which number is between the other two.

i.e. given 3,5,2 I need 3 to return.

I tried to implement this by going through all three and using if else conditions to check if each of the other two is. But this seems like a naive way to do it. Is there a better way?

+5
source share
9 answers

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

+17
source
>>> x = [1,3,2]
>>> sorted(x)[len(x) // 2]
2
+11
source

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
+8

numbers = [3, 5, 2]
sorted(numbers)[1]
+4

, . :

import numpy
numbers = [3,5,2]
median = numpy.median(numbers)

.

+3

This is an implementation of the O (n) median using cumulative distributions. This is faster than sorting, because sorting is O (ln (n) * n).

def median(data):
    frequency_distribution = {i:0 for i in data}
    for x in data:
        frequency_distribution[x] =+ 1
    cumulative_sum = 0
    for i in data:
        cumulative_sum += frequency_distribution[i]
        if (cumulative_sum > int(len(data)*0.5)):
            return i
+3
source

Check this out (suppose the list is already sorted):

def median(list):
    ceil_half_len = math.ceil((len(list)-1)/2)   # get the ceil middle element index
    floor_half_len = math.floor((len(list)-1)/2) # get the floor middle element  index'
    return (list[ceil_half_len] + list[floor_half_len]) / 2
+1
source

Here is my attempt to use a more pythonic version

def median(a):
    sorted_a = sorted(a)
    if len(a) % 2 == 0:
        median = sum(sorted_a[(len(a)//2)-1:(len(a)//2)+1])/2.
    else:
        median = sorted_a[(len(a)-1)//2]

>>> x = [64630, 11735, 14216, 99233, 14470, 4978, 73429, 38120, 51135, 67060]
>>> median(x)
>>> 44627.5
>>> y = [1, 2, 3]
>>> median(y)
>>> 2
0
source

If you want to avoid sorting, you can do:

def find_median(x):
    return sum(x) - max(x) - min(x)
0
source

All Articles