This is the quiz:
The function in this quiz, median, returns the median value of an input list. Unfortunately it only works with lists that have an odd number of elements. Modify the function so that when median is given a list with an even number of elements, it returns the mean of the two central elements. The provided test cases demonstrate the expected behavior.
The function in this quiz, median, returns the median value of an input list. Unfortunately it only works with lists that have an odd number of elements. Modify the function so that when median is given a list with an even number of elements, it returns the mean of the two central elements. The provided test cases demonstrate the expected behavior.
def median(numbers): numbers.sort() #The sort method sorts a list directly, rather than returning a new sorted list middle_index = int(len(numbers)/2) return numbers[middle_index] test1 = median([1,2,3]) print("expected result: 2, actual result: {}".format(test1)) test2 = median([1,2,3,4]) print("expected result: 2.5, actual result: {}".format(test2)) test3 = median([53, 12, 65, 7, 420, 317, 88]) print("expected result: 65, actual result: {}".format(test3))That's my answer:
def median(numbers): numbers.sort() if len(numbers)%2: middle_index = int(len(numbers)/2) return numbers[middle_index] else: middle2 = len(numbers)/2 return (numbers[middle2]+numbers[middle2-1])/2And this is the error that i get:
Error:Traceback (most recent call last):
File "vm_main3.py", line 47, in <module>
import main
File "/tmp/vmuser_uohknylyuz/main.py", line 2, in <module>
import studentMain
File "/tmp/vmuser_uohknylyuz/studentMain.py", line 1, in <module>
import median
File "/tmp/vmuser_uohknylyuz/median.py", line 13, in <module>
test2 = median([1,2,3,4])
File "/tmp/vmuser_uohknylyuz/median.py", line 8, in median
return (numbers[middle2]+numbers[middle2-1])/2
TypeError: list indices must be integers, not float
expected result: 2, actual result: 2