Mission 306-4: An alternative approach; possibilities of errors?

I used a slightly different approach from the dq solution; My question is whether my approach is correct or it only works in some situations and not in others.
I hope to learn from users if my understandings of the principles is correct.

Screen Link:

My Code:

rooms_above_ground = rooms_above_ground.replace('10 or more',10)
rooms_above_ground = rooms_above_ground.astype('int64')
rooms_above_ground = rooms_above_ground.sort_values()

def what_is_the_median2(lst):
    print(len(lst))
    if (len(lst) % 2) == 0:
        return (lst[len(lst)//2-1] + lst[len(lst)//2])/2
    else:
        return lst[len(lst)//2]

mylst = rooms_above_ground.sort_values().tolist()

what_is_the_median2(mylst)

What I expected to happen:

2930

Out[126]:

6.0


What actually happened: 

2930

Out[126]:

6.0

<!--Enter other relevant details below: -->
I used the function to first identify the indices, similar to the dq approach, but only with scalar quantities rather than using pandas ) iloc etc.). 
I used floor division to get the numbers of the indices. 
Is it possible that in some situations the number for indices may be off?
2 Likes

Hi @saleemdar.dr, I don’t understand what your question is but your code actually worked when I tried it, you didn’t follow the last instruction in the exercise which says you should assign it to a variable named median.

2930 you got was as a result of this code, inside your function you told it to print the length of the lst that’s why you got it but your median is ver correct.

1 Like

thank you for the reply.

yes it does work. my question was that are there any hidden caveats that may not have occurred to me and that make the code specific to this situation and not applicable generally.

In my experience some solutions may work in a particular situation but are not applicable generally to all cases.

1 Like

Hard to say.

Try making two versions of mylst - one with odd length and the other with even length. And pass the two list into the function. See if the results make sense.

After that, compare the results with pandas’ median calculation or maybe with a median function from other statistics library (I’m not sure if Python has a built-in median).

1 Like

thanks for the answer; I did that already and it works;

1 Like

Ah, I see. That’s fine then.

If the results for both cases are similar to the results from other libraries, you function should be fine. If you’re up for it and if the library is open-sourced, you can also directly read the source code for the median function whether it’s in pandas or something else and compare the code with your function.

I believe that would satisfy you the most because those libraries are used by many people and should be reasonably correct i.e. if your implementation is similar to other popular libraries then your implementation is most likely correct.

2 Likes