Median improvement


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
        return nums[len(nums)/2]


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


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.


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


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


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?


Nah, it's all clear.


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