#1

stuck at exercise 15 median in python

error message median([6,8,12,2,23])resulted in error :list index out of range.

i don't why it is not working.the first line is def median(l)

``````    sl = sorted(l)
c = len(sl)
if c == 1:
return l[0]
if c % 2 == 1:
middle_index = sl[int(c - 1) / 2]
middle_value = sl[middle_index]
return middle_value
else:
middle_index1 = sl[int(c / 2 - 1)]
middle_index2 = sl[int(c / 2)]
middle_value = (middle_index1 + middle_index2) / 2.0
return middle_value

Replace this line with your code.``````

#2

When we see repeated code patterns in the body of conditional branches, it usually indicates that simplification is feasible, with most computation to be done before the conditional.

``````sorted_sample = sorted(sample)
n = len(sample)
m = int(n / 2)``````

In Python 2, `int(n / 2)` and `n / 2` yield the same result as long as `n` is an integer.

``````if n % 2:
return sorted_sample[m]``````

That takes care of the odd length list, including length of 1. No need to check for that case.

``return float(sorted_sample[m - 1] + sorted_sample[m]) / 2``

The even length list is handled with that line. Done like dinner.

#3

Beautiful,clean and simple. Can you please explain what n % 2: mean and why we don't have to put a value like n % 2 == 1(though code works with this also). Also why if n = 5 m = int(n / 2) gives 2 and not 2.5 or 2.5 rounded to 3. Thanks for help

#4

When `n` is odd, `n % 2` will be non-zero, which casts to `True` in a boolean expression (`if` yields a boolean).

Because of the `int()` function. However, in Python 2, the result of 5 / 2 will be `2`, anyway since that is how integer division is interpreted. By writing the `int()` function, it becomes explicit that the desired result is an integer. That is how it is done in Python 3.

#5

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