Median (my code worked but I don't understand why it did)


#1


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


I think the code c=b-1 should rather be c=b+1.


def median(numbers):
    st=sorted(numbers)
    med=0
    b=len(numbers)/2
    c= b-1
    if len(numbers)%2==0:
        med=float(st[b] +st[c])/2
        return med
    else:
        return st[b]


#2

Your code works fine because your first variable b halves the array length. In the notes for the exercise it says, not explicitly but I have to assume that the array / list passed to your code is of EVEN length.

{c=b-1} is absolutely correct and explained in the hint:

'You can find the middle two elements by halving the length of the array to find the index of the first element, and subtracting one from the first index to find the second index.'

I hope that makes sense :slight_smile:


#3

Let's think about a list with four items l=[W, X, Y, Z]
len(l) will be 4
len(l)/2 will be 2
You store this one in your variable c
now simply count and remember: first item of a list has the index 0 (THIS IS WHY c-1 IS CORRECT!)
0=W
1=X -> c
2=Y -> b
3=Z


#4

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