Problem in Median


#1

This is my code to find the Median.. but I am getting error as "Oops, try again. median([1]) returned [1] instead of 1"

def median(number_list):
    modified_list = []
    for num in  number_list:
        modified_list.append(num)
        return modified_list
    sorted_list = sorted(modified_list)
    list_length = len(modified_list)
    
    if list_length % 2 == 0:
        middle_term_1 = list_length/2 + 1
        middle_term_2 = list_length/2
        median_term = (float(sorted_list[middle_term_1] + sorted_list[middle_term_2])) / 2
    else:
        median_term = sorted_list[(number_list + 1)/2] 
    return median_term
    
    
print median([5, 2, 3, 1, 4])    
print median([5, 2, 3, 1])

Also, the result for the last two examples is 5 for both..

Please help.


#2

a function returns None by default at end, if you want the function to return something else you can use return keyword to return something different.

This means that a function ends the moment a return keyword is reached, looking at your code, where is this happening?


#6

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