Median improvement


#1




It works but is there a way to improve this?


def median(nums):
    nums = sorted(nums)
    if len(nums)%2 == 0:
        return float(nums[len(nums)/2-1]+nums[len(nums)/2])/2
    else:
        return nums[len(nums)/2]


#2

improve in what way? There are few minor changes you can make, but not much without compromising readability.


#3

It looks kinda messy. I thought there might be a better way to do this exercise. It's hard to tell since there's no answers.


#4

it is always the balance between readability, maintain-able and so on.

If you want to increase on readability you could make the code in a few more lines:

def median(nums):
    nums = sorted(nums)
    length = len(numbs)
    if len(nums)%2 == 0:
        left_middle = length / 2 -1
        right_middle = length / 2
        total = nums[left_middle] + nums[right_middle]
        middle = total /2.0
   else:
        middle = nums[length/2]
   return middle

okay, this might go a bit far, but it makes the code much readable. Using good variable names also helps


#5

Cool. Thanks. I can see a few things I could do better.


#6

yea, you can fiddle a bit with this code to get something you like :slight_smile:

I did nothing weird or new here which requires explaining, right?


#7

Nah, it's all clear.


#8

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