Median exercise

It points to some syntax error but i can't find it. Line 5 it says.

```
def median (a):
a.sort()
if len(a)%2==0:
return ((a[(len(a))/2.0]+a[(len(a))/2.0-1])
else:
return a[len(a)/2]
```

Median exercise

It points to some syntax error but i can't find it. Line 5 it says.

```
def median (a):
a.sort()
if len(a)%2==0:
return ((a[(len(a))/2.0]+a[(len(a))/2.0-1])
else:
return a[len(a)/2]
```

The error is pointed out on line 5 but is actually in line 4. Count the `(`

's, 6. Count the `)`

's, 5. A number of those brackets are not needed.

`(a[len(a)/2.0]+a[len(a)/2.0-1])`

This brings up a tiny issue with repetition. `len(a)/2`

appears three times, suggesting a temporary variable might be helpful. Note that you have not divided that sum by 2.

`n = len(a)`

Implicitly massaging a number to a float by dividing by 2.0 is not as useful as it might appear. Explicit declarations are preferred since there is no ambiguity.

```
m = int(n/2)
if n % 2: return a[m]
return float(a[m-1] + a[m]) / 2
```

Python 2 lets us get away with expecting an integer result when dividing integers. Python 3 does not. Just like floats, explicit integer declarations leave no doubt in the reader's mind. Something to keep in mind as we migrate to Python 3.

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