# Media problem

#1

Hello,
Any idee what i do wrong ?

Oops, try again. median([4, 5, 5, 4]) returned 4 instead of 4.5

When i run it in an interpretor with the same list as input parameter it returns 4,5

``````def median(lista):
lista = sorted(lista)
a = 0
for i in lista:
a = a+1
new = []
if a % 2 == 1:
jumate = (a/2)-0.5
jumate = int(jumate)
new = (lista[jumate:jumate+1])
for i in new:
return i
else:
jumate1 = (a/2)-1
jumate2 = (a/2)+1
jumate1 = int(jumate1)
jumate2 = int(jumate2)
lista = lista[jumate1:jumate2]
suma = 0
for i in lista:
suma = suma + i
medie = suma / 2
return medie``````

#2

``````\$ python3 -i digitalwhiz30107.py
>>> median([4, 5, 5, 4])
4.5
\$ python2 -i digitalwhiz30107.py
>>> median([4, 5, 5, 4])
4``````

``````import sys
print(sys.version)``````

Use print statements to follow in what it does

#3

Your code is too convoluted. Try to understand my code, I have used two functions to make it more plain.
If you have any questions, just ask.

``````def average(b, c):
m=float((b+c))/2
return m

def median(lst):
lst=sorted(lst)
y=len(lst)
if y%2==0:
x=average(lst[y/2], lst[(y/2)-1])
else:
x=lst[(y/2)]
return x``````

#4

Their code isn't convoluted, it's just not mashed together into ten actions per line. For the purpose of designing and implementing an algorithm it's perfectly fine. A later step would be to look for unnecessary operations, things that cancel each other out etc, but until it has been figured out what the code should do, there's no point in trying to make it short at the same time as trying to make it work. It's also very easy to insert print statements when it's spread out this way, to observe what it does.

#5

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