Oops, try again. median([1]) returned 0.5 instead of 1

Please help.

```
def median(a):
if len(a) % 2 == 0:
average = (len(a) + 1) / 2.0
else:
sorted(a)
average = len(a) / 2.0
return average
```

Oops, try again. median([1]) returned 0.5 instead of 1

Please help.

```
def median(a):
if len(a) % 2 == 0:
average = (len(a) + 1) / 2.0
else:
sorted(a)
average = len(a) / 2.0
return average
```

i would sort the list first, before doing anything else. If you use sorted(), make sure to store the sorted list into a variable

here:

`average = len(a) / 2.0`

this will give you the middle index, not the middle value. Given its an index, divide by 2 (not 2.0) since indexes should be integer. Use this index to retrieve the middle value

I have tried to do this, still doesn't work.```

def median(a):

```
sort = sorted(a)
if len(a) % 2 == 0:
average = (len(a) + 1) / 2.0
else:
average = len(a) / 2
return average
```
```

here:

`average = len(a) / 2`

now average contains the middle index, but the median is the middle value. Use the index to retrieve the value from the list

well for example for:

`[3, 5, 7]`

your average would contain the middle index:

`average = len(a) / 2`

which is 1. but the median is the middle value (5), so you need to use the index, to retrieve the middle value

You're really good at explaining it, but Python frustrates me like anything and I can't do it, This doesn't work.

```
def median(a):
sort = sorted(a)
if len(a) % 2 == 0:
average = (len(a) + 1) / 2.0
else:
average = abs(len(a) / 2)
return average
```

now average still contains the middle index, tell me, how do we get from list index to list value? If you don't know, feel free to google or check earlier lessons

i assume this is known, given you have done it many times before

The error message is:Oops, try again. median([4, 5, 5, 4]) resulted in an error: list indices must be integers, not float

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

better, but not exactly there yet. For even lists, you need to get the left (4) and right (5) middle value, add them together (don't forget parentheses, order of operation) and divide by 2.0

Thanks so much, I followed your advice for the even list, but I had to get the else bit from someone else's answer. If possible, please could you explain the else bit?

I feel like I'm pasting code half the time which is really bad.```

def median(a):

```
sort = sorted(a)
if len(a) % 2 == 0:
right = len(sort) / 2
left = (len(sort) / 2) - 1
average = (sort[right] + sort[left]) / 2.0
else:
average = sort[len(sort) / 2]
return average
```

```

the else line isn't much difference from what you did? except its all compressed in a single line

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