T
Tyson_Codes
Guest
Tyson_Codes Asks: how to avoid a type error when finding the median of a list
I am working on a project to get the mean, median and mode of a list. I have it almost all down but the median function is giving me the following error: return (list[midIndex]+list[midIndex-1])/2.0 TypeError: list indices must be integers or slices, not float
`
`
The answer should be 3.5 but I'm in the middle of a final week all night study bender and my brain is not functioning properly. Caffeine is failing me right now and I would love if anyone could find the error for me.
I am working on a project to get the mean, median and mode of a list. I have it almost all down but the median function is giving me the following error: return (list[midIndex]+list[midIndex-1])/2.0 TypeError: list indices must be integers or slices, not float
`
Code:
def median(list):
if len(list) == 0:
return 0
list.sort()
midIndex = len(list)/2
if len(list)%2 == 0:
return (list[midIndex]+list[midIndex-1])/2
else:
return list[midIndex]
def mean(list):
if len(list) == 0:
return 0
list.sort()
total = 0
for number in list:
total += number
return total / len(list)
def mode(list):
numberDictionary = {}
for digit in list:
number = numberDictionary.get(digit, None)
if number == None:
numberDictionary[digit] = 1
else:
numberDictionary[digit] = number+1
maxValue = max(numberDictionary.values())
modeList = []
for key in numberDictionary:
if numberDictionary[key] == maxValue:
modeList.append(key)
return modeList
def main():
lyst = [3, 1, 7, 1, 4, 10]
print("List:", lyst)
print("Mode", mode(lyst))
print("Median:", median(lyst))
print("Mean:", mean(lyst))
main()
`
The answer should be 3.5 but I'm in the middle of a final week all night study bender and my brain is not functioning properly. Caffeine is failing me right now and I would love if anyone could find the error for me.