# Median - Could I have written this in less lines?

#1

This is probably the first exercise that I did all on my own without looking up any help. So, I'm very happy to have made this progress with Python. However, I know that this could've probably been done with less lines and much simpler.

Any suggestions on how this could have been done with less lines? I'm looking to improve on my "noob" skills.

``````def median(data):
newlist = sorted(data)
size = len(newlist)
oddmedian= (size -1)/2
if size%2 == 0:
b = size / 2
c = b - 1
second_digit = newlist[b]
first_digit = newlist[c]
median = (second_digit + first_digit)/2.0
return median
elif size % 2 == 1:
return newlist[oddmedian]``````

#2

lesser lines doesn't always mean better. If it compromises readability, the code becomes more difficult to maintain.

I mean you can reduce this:

``````        b = size / 2
c = b - 1
second_digit = newlist[b]
first_digit = newlist[c]
median = (second_digit + first_digit)/2.0
return median``````

if you want:

``return (newlist[size/2] + new_list[size/2-1]) / 2.0``

This still readable, so it might be better

But you should be proud you solved it

You can always come back later and try it again, see how much you improved

#3

Got it. So readability is more important, over less lines. Thank you for that. Yes, your suggestion definitely removes about 5 lines but increases complexity.

#4

no, its important to have a good balance between readability, performance and lines of code. This is always tricky, for different jobs/task the priority of which is important might shift/be different

its always a trade-off, ideally (which doesn't exist) you want to have the best of both worlds

#5

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