Whats wrong with my code? 15.median


#1



Whats wrong with my code?

https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#

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


def median(lavuk):
    lavuk = sorted(lavuk)
    index_number = 0
    median_score = 0
    for n in lavuk:
        index_number = index_number + 1
    return index_number
    
    if (index_number % 2) == 0:
        median_score =(lavuk[(index_number/2.0)]+lavuk[(index_number/2.0)+1])/2.0
    else:
        median_score = lavuk[(index_number + 1) / 2.0]
    
    return median_score


#2

Where is the first return statement? At the close of the loop. The SCT passed in a list with 4 elements, the loop counts those and returns 4. To the SCT it looks like a computational error when in fact it is a procedural error. A list of eight items will retun 8.

Not a little bit juvenile? We know what lavuk means in one language, and it is rather derogatory. Perhaps choose a variable name that actually applies and describes its role in the function.


#3

@sadesoda:

Other than what @mtf said, just a few remarks about your code.

This will force your program to go back to where the function was once called so I'd suggest removing it.

This doesn't seem right at all.
lavuk seems to be your list and such won't accept indexes where the value is a float, a.k.a. contains a decimal part, and dividing a number, float or int, by a float, will get you a float.

print 1/2 # 0
print 1/2.0 #0.5
print 1.0/2 # 0.5
print 1.0/2.0 #0.5

I'd suggest listening to what @mtf mentioned and checking the instructions once again.


#4

Opinion

Consider, when we divide a value into equal parts, we divide by the counting number that describes how many parts. A counting number, such as 2 is an integer. We don't write a fraction,

1 / 4.0

we write,

1 / 4

If we need the quotient to be a float, then we declare the numerator as a float, and divide by the counting number, like normal. Converting a counting number just does not make any logical or mathematical sense, at least not to me.

float(n) / 2

gives a float, without manipulating the counting number. And, it is explicit.


#5

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