# 15. Median

#1

My code works...Its ugly and probably not the best way to solve this problem...I feel like there is a better way to do this than the way that I did. I would appreciate any feedback as to what I could or should do differently in the future so that I come up with the best possible solutions.

Oh, for some reason the line div = (div + i) / 2 returns the incorrect answer when I did it on one line....

``````def median(nums):
numbers = sorted(nums)
mid_point = len(numbers) / 2
if len(numbers) % 2 != 0:
num = 0
numbers = numbers[mid_point:mid_point + 1]
for o in numbers:
num = num + o
return num
else:
div = 0.0
numbers = numbers[mid_point - 1:mid_point + 1]
for i in numbers:
div = div + i
divide = div / 2
return divide``````

#2

here are some tips, you need to divide the code into two sections (you did this), one for lists with even amount of items, one for odd amount of items in the list.

for even lists (list with even number of items/numbers) you need the two middle items. Lets say our list has 4 numbers, the numbers you need are at index 1 and 2. Or 4 (length of list) divided by two, and list/2-1. You can do the math, but the same goes for a list with 8 numbers: indexes are 0 till 7 (7 included) so the middle once are 4 and 3 (8/2=4, 8/2-1=3), so you can just take the sum of these two numbers, and then divide them by two (of sorts, you will need to divide by a float or cast it to a float, otherwise you will get a integer)

For odd lists it is even easier. the length of the lists divided by two will always give you the middle number. list is 3 in length, indexes are 0,1,2. 3/2=1, so you have the middle one. Same for 1 (1/2=0, which is the index you need), 5,7, and all higher numbers