Cleaner way of doing the Median task



This is the kind of monstrosity I ended up creating:

def median(foobar):
    foo = sorted(foobar)
    if len(foo) == 1:
        return foo[0]
    elif len(foo) % 2 == 0:
        a = foo[: int(len(foo) / 2.0)]
        b = foo[int(len(foo) / 2.0) :]
        return (a[len(a) -1] + b[0]) / 2.0
    elif len(foo) % 2 != 0:
        c = foo[int(len(foo) / 2.0) :]
        return c[0]

Without importing other modules, how could I have made this cleaner?



foo = sorted(foobar)

we could use .sort() which is a method specific for lists:


which will update the list for us, so we don't have to store the result it in a variable


    if len(foo) == 1:
        return foo[0]

not needed, length (1) divided by 2 gives 0, which is the index we need to get the "middle" (only) value

for lists with even length we can calculate the middle two indexes (length / 2 and length / 2 - 1), use this indexes to retrieve the values from list, add them together and divide them by 2.0

for lists with uneven length we can get the middle index (length/2), this also works for [1]

that is pretty much it

to retrieve a value based on index:

a = [1,2,3]
print a[1]

no need to use : which gives list slicing


what you can do is use floor division (//):

print (3 // 2)
print 3 // 2

which yields the same result (1) in both versions of python

also, you don't need this:

or len(foobar) == 1

your conditions can handle it (1 % 2 is 1, so its fine)

and this:

elif len(foobar) % 2 != 0:

this coulbe else, given a number is odd or even, there are no other scenarios.

honestly? I don't know for sure, but i think the design is on purpose, either way, we can use it nicely to our advantage :slight_smile:


yes, in python2 1/2 is 0

by using elif in the median, another condition has to be checked, while you know the only remaining possible case is lists of uneven length, so it would save you a condition check if used else, you can include a comment to remind you what it does

yes, elif is used if we want to catch a specific input/scenario


i don't know, for me programming is a hobby.

i have never done a project which included more then 5000 lines of code


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.