Media problem


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


$ python3 -i 
>>> median([4, 5, 5, 4])
$ python2 -i 
>>> median([4, 5, 5, 4])

import sys

Use print statements to follow in what it does


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):
    return m 

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


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.


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