On 21/9/2013 02:07, William Bryant wrote: In addition to Steven's comments:
> > def median(): > medlist = List > medlist.sort() You have just altered the original list. Perhaps sorting it is harmless, but below you actually remove elements from it. One way to avoid that is to use the sorted() method, which creates a new list. > if len(medlist) % 2: This then is the "odd" size branch of code. I think you intended to do the reverse if-test. A comment would be in order. > while len(medlist) > 2: > medlist.popleft() > medlist.popright() At this point, there is exactly one item left in the list. So the code below is going to get into trouble. > if medlist[0] == medlist[1]: > themedian = medlist Is the return value of this function supposed to be a list, or a float? If a float, then you should be doing something like: themedian = medlist[0] > elif medlist[0] != medlist[1]: > #make an if statment to figure out the median if the last 2 left > are not the same. Eg [1, 2] the middle value is 1.5 > pass > else: > while len(medlist) > 1: > medlist.popleft() > medlist.popright() > themedian = medlist > return themedian > > It says out of range and i don't know how I am going to make an if statment > to figure out the median if the last 2 left are not the same. Eg [1, 2] the > middle value is 1.5. Thanks - I am 13 year old beginner in python and i am > trying to finish the tutorial on code academy and read the docs. :) Taking Steven's suggested code, and changing it so it uses a COPY of the global list; def median(): # Relies on the global variable called List. # assumes there is at least one number in that list numbers = List.sorted() n = len(numbers) if n % 2 == 1: # Odd number of items. return numbers[n//2] else: a = numbers[n//2 - 1] b = numbers[n//2] return (a + b)/2.0 -- DaveA -- https://mail.python.org/mailman/listinfo/python-list