15/15, the hard way


Hi, guys,

I'm trying to work through the last set here and create a median function. I forgot about the sorted function until I started browsing these forums. I'll use that now and I think I can crack the problem, but in the meantime I would appreciate an explanation of why my code screws up. You'll find it below. The idea is that you create a new list, dropping off each new number in just the right spot. To start with I add -9 and 999 to the list. You can think of them as bookends. After all the median function should only pay attention to the middle number (or middle two numbers), so it doesn't matter if the new list is a little more swollen.

But I can't seem to insert the numbers in the list in the write spot. The problem in the code below is the 8th line. My understanding is that when you generally insert( list [index]), it inserts at the indexed location, and then everything else past that moves down. But for whatever reason it inserts the number at the end of the list. Every time. And if I tweak it even a little to just ordered.insert(ordered[i], number) vs. the original ordered.insert(ordered[i+1], number), the numbers all get inserted before even -9.

Why is it not inserting in the right spot?

def median(sequence):

ordered = []
for number in sequence:

i = 0
while i <= len(ordered):

if ordered[i] <= number and number <= ordered[i+1]:

ordered.insert(ordered[i+1], number)
print ordered
i += 7

i += 1

return ordered

print median([7,12,3,1,6])

Sorry, not sure how to indent properly, but hopefully you get the idea this way.


list.insert(index, value)

You're not specifying the index that you want to put the value at. You use your index to look up some other value.

If the index is len(the_list) or higher, it gets added to the end.

a = []
a.insert(9001, 4)
print a    # [4]

There's a button for preserving the format of code. It's helpful if the code in your post is exactly the same as yours with no modifications whatsoever. Details matter.