# 15 median -- is my solution better?

#1

I wrote this code :

``````def median(lst):
lst = sorted(lst)
amo = len(lst)
fin = 0
if amo % 2 == 0:
fin = float(lst[amo / 2] + lst[amo / 2 - 1]) / 2
else:
fin = int(lst[amo / 2])
return fin
``````

and then decided to look at solution :

``````def median(lst):
sorted_list = sorted(lst)
if len(sorted_list) % 2 != 0:
index = len(sorted_list)//2
return sorted_list[index]
elif len(sorted_list) % 2 == 0:
index_1 = len(sorted_list)/2 - 1
index_2 = len(sorted_list)/2
mean = (sorted_list[index_1] + sorted_list[index_2])/2.0
return mean

print median([2, 4, 5, 9])

``````

but it looks so complex, so I’ve got a question: is my code better??

#2

Some of the solutions proposed by codecademy are not the best indeed. Yours is certainly more readable

in your code, i would get rid of `fin = 0`, it doesn’t add much value.

the user of floor division:

``````index = len(sorted_list)//2
``````

and using `2.0` to ensure float value:

``````mean = (sorted_list[index_1] + sorted_list[index_2])/2.0
``````

so we don’t get casting with `int()` and `float()`.

You could consider to not use `fin` at all, just do `return lst[amo // 2]`

also, its no shame to use longer variable names, longer variables are actually better. Makes it easier to understand what the variable do. If you have to refactor your code two months later, you will be grateful to yourself (or an earlier developer) that they used proper descriptive variable names

#3

If you have to refactor your code two months later, you will be grateful to yourself (or an earlier developer) that they used proper descriptive variable names

ahah, thanks, this is nice advice)
also I haven’t sorted out with floor division, so I don’t actually understand what it means thanks again

#4

literally what is say, python will floor the number (round down to the nearest integer). floor division is done using two forward slashes (`//`) oppose to the one forward slash of regular division (`/`)

If you don’t know something, you can always google it.

#5

certainly, I could google it, but actually I didn’t even know about it

#6

The given code looks more complex but actually reads very clear.
While you’ve certainly shortened a lot of statements, you’ve also taken away a lot of information.

Ambiguously named variables like lst amo and fin may make sense to you at the time, but they might not a month from now. They certainly leave a lot of guess work up to the next programmer who works on your code. Naming variables is an art of sorts. Try to be as clear as possible.

#7

Looks like this point is really necessary in future career. All right, I’ll try to follow this rule(?) in my code. Thanks for advice

#8

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