Practice Makes Perfect: Median ; Lesson 15/15


#1

Hello.

Taking ([0,1,2,3,4,5]) as an example

Can someone please explain to me how the part of the circulated code (in red ) below:

lst.index(len(lst)/2 -1)

evaluates to 2.

Properly speaking wouldn’t it evaluate as follows;

lst.index(len(lst)/2 -1)

= lst.index(len(lst)/ 1)

which would give you the whole list and not the 2nd portion of it.

Shouldn’t the right code be lst.index((len(lst)/2) -1)


#2

In math class, i learned something called order of operations:

http://www.purplemath.com/modules/orderops.htm

which can be remembered as PEMDAS:

  1. Parentheses (simplify inside 'em)
  2. Exponents
  3. Multiplication and Division (from left to right)
  4. Addition and Subtraction (from left to right)

division comes before subtraction.

why would subtraction come before division?


#3

I was reading the " 2 - 1" as a separate statement from lst.index(len(lst)/2 -1) that should be evaluated first for purpose of simplification.

For example 50 / 5 - 2 is different from 50/ (5 -2).

But okay, perhaps the confusion shouldn’t come up anyway since we are told in the hint to do the division first; "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. Without the hint direction, I just felt that that part of the code could be mistaken as 50/ (5 -2) rather than 50 / 5 - 2.

Anyhow my bad, PEMDAS and all. And thanks for the explanation


#5

Which in turn probably isn’t useful for computing the median


#6

True, given index find the first match it can find. I didn’t even notice, i focused on the users question


#7

Right but there aren’t parentheses around 2 - 1
There do exist languages that evaluate from left to right regardles of which the operators are (unless parentheses are used), but right to left is probably rare

You’ve also got . and call () operators in there, they have pretty high precedence though, to the point where people barely consider them to be operators


#8

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