HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Median Calculator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mediancalculatorstackoverflow

Problem

This is just a simple median calculator that calculates the median for a given array/list.

def median(lst):
    nl = []
    nl = sorted(lst)
    e = int(len(nl))
    if e % 2 != 0: # True if odd # of #'s
        ind = int(((e / 2.0) - 0.5)) # index of the median
        c = nl[ind]
        print c
    else: # even # of #'s
        ind_left = int(e / 2.0) - 1 # index left of median
        ind_right = int(e / 2.0) # index right of median
        z = (nl[ind_left] + nl[ind_right]) / 2.0
        print z

median([4, 4, 5, 5, 2.5])

Solution

Please name your variables appropriately. Single-letter variables are in most cases sub-optimal and make it needlessly hard for the you-in-six-weeks to figure out what it does.

I'm fairly sure your algorithm is sub-par as well, although I'm not that proficient in algorithms myself. I suspect a function like this already exists in the Python library, I'll update this answer when I've found it.

The following is double work:

nl = []
nl = sorted(lst)


The following will suffice:

nl = sorted(lst)


If you'd be using Python 3.4 or higher, statistics.median would solve your problem.

In Python 2.7 you'll have to install NumPy, an often used library for large number calculations. Now use numpy.median like this:

import numpy as np
def median(lst):
    return np.median(np.array(lst))

print(median([4, 4, 5, 5, 2.5]))


Python usually has basic functions like this already available to you. If it's already available in commonly used Python libraries, it's usually a good idea not to re-invent the wheel yourself.

Code Snippets

nl = []
nl = sorted(lst)
nl = sorted(lst)
import numpy as np
def median(lst):
    return np.median(np.array(lst))

print(median([4, 4, 5, 5, 2.5]))

Context

StackExchange Code Review Q#149409, answer score: 12

Revisions (0)

No revisions yet.