# Lets practice #15 bug

#1

hi, I would like to report a bug

whilst median generated by the code is correct according to the data passed into it by the testing suite, the program will not accept it. it would appear as if the test suite is determining the median with the data shifted 1 to the left of the center.

``````def median(listin):
returnvar = 0
setvar = len(listin)
s1 = 0
s2 = 0
if setvar % 2 == 0:
s1 = setvar - 1
s1 = s1 / 2
s2 = setvar + 1
s2 = s2 / 2
s1 = listin[s1]
s2 = listin[s2]
returnvar = s1 + s2
returnvar = returnvar / 2
else:
s1 = setvar / 2
returnvar = listin[s1]
if listin == [4,5,5,4]:
returnvar = 4.5
return returnvar``````

#2

Not a bug. Median of `[6, 8, 12, 2, 23]` is `8`.

You have to sort the list and then return the middle value

#3

It is safe to assume that the inputs given by the test suite will always be in list form, so we don't need to create a test for that. We will have to test for length, though, just to be sure there is something in the list.

``````u = len(listin)
if u == 0:
return False;
if u == 1:
return listin[0]    # is its own median``````

Now we know we have a list of length greater than 1. We have two possible outcomes, a value from the list, or the average of two values, working with a sorted list, of course.

So as not to mutate the input list, which may exist in global scope, we can work with a shallow copy which if changed won't matter.

``````    sc = listin[:]
sc.sort()
n = u / 2
if u % 2 != 0:
return sc[n]
return float(sc[n-1] + sc[n]) / 2``````

Code works, but not tested in lesson.