Need help with Median


The exercise is called Practice makes perfect: Median

The error message displayed was, "median([4, 5, 5, 4]) resulted in an error: int() argument must be a string or a number, not 'list'".

I know that you can't use the int function on a string, which is what I am trying to do in my code and that is why it is not working. However, I do not know how to change my code so that it still does what I want it to do with the proper numbers becoming integers. Basically what I am wondering is how do you make a list into an integer.

Replace this line with your code. 

def median(lst):
    x = []
    if len(lst) % 2.0 == 0:
        y = 0
        y+=int([len(lst) / 2.0])
        y+=int([(len(lst) / 2.0) - 1])
    elif len(lst) == 1:
        x.append([len(lst) / 2.0])
    return x[0]


Here is my code - might be of some help to you (could be written better but I think such things come with practice):

def median(x):
X = sorted(x)
result = []
if len(X) == 1:
result = sum(X)
elif len(X) % 2 != 0:
result = sum(X[(len(X)-1)/2: (len(X)+1)/2])
result = sum(X[(len(X)-2)/2: (len(X)+2)/2])/float(2)
return result


You can use the sorted(lst) function to sort your list.
You don't need to convert any string to integers. You don't need to deal with strings in the first place as the list your are inputting is a list of integers.
You can set two conditions:
One where the length of your list is even, and one where the length is not. Then use the list[index] to pick out the median:
Even length list:

(lov[(len(lov)/2) - 1] + lov[(len(lov)/2)]) / 2.0 #lov = sorted list of values

Odd length list:

lov[int(len(lov)//2)] #lov = sorted list of values

def median(x):
    x = sorted(x)                  #sort list x         
    if len(x) % 2 != 0:            #if number of indices in x are odd, return middle indice [x, x, X, x, x]
        return x[len(x)/2]
        return (x[len(x)/2] + x[(len(x)/2)-1]) / 2.0         #otherwise, add the right mid indice to the left mid indice, divide that number by 2.0, and return the result [x, x, X, X, x, x]


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