######################################################################## ######################################################################## # # MeanModeMedian.py # write a function to return the mean, mode and median of the following # numbers # ######################################################################## ######################################################################## # 1000 numbers taken from a Poisson distibution numbers = [ 5, 5, 6, 5, 3, 3, 7, 5, 4, 4, 3, 4, 5, 3, 3, 2, 2, 7, 7, 7, 5, 7, 10, 3, 2, 2, 6, 7, 10, 6, 7, 6, 5, 3, 5, 4, 4, 4, 2, 7, 6, 6, 5, 11, 5, 7, 3, 9, 5, 2, 5, 12, 7, 8, 6, 2, 1, 5, 5, 6, 5, 8, 4, 6, 4, 5, 4, 5, 5, 5, 7, 4, 4, 2, 2, 6, 5, 6, 7, 3, 8, 8, 10, 6, 7, 6, 6, 3, 5, 9, 2, 4, 6, 7, 7, 4, 5, 4, 8, 5, 5, 4, 7, 8, 4, 10, 4, 1, 9, 7, 10, 7, 1, 8, 7, 6, 1, 11, 6, 5, 6, 3, 7, 3, 4, 6, 6, 4, 7, 5, 6, 2, 2, 7, 3, 8, 4, 5, 8, 4, 5, 2, 7, 4, 7, 7, 4, 4, 7, 1, 3, 11, 3, 4, 2, 5, 4, 4, 4, 4, 8, 10, 8, 2, 4, 6, 0, 7, 4, 5, 8, 6, 6, 4, 5, 8, 8, 6, 5, 8, 11, 4, 6, 6, 2, 5, 2, 5, 2, 6, 4, 9, 7, 10, 6, 2, 11, 8, 5, 1, 4, 5, 3, 5, 4, 3, 8, 0, 6, 13, 5, 3, 8, 3, 6, 8, 2, 4, 4, 4, 4, 2, 2, 6, 5, 7, 2, 6, 7, 2, 4, 6, 5, 4, 12, 4, 9, 1, 12, 5, 6, 11, 6, 8, 9, 2, 9, 3, 5, 10, 7, 8, 6, 4, 7, 6, 7, 5, 4, 2, 8, 4, 1, 8, 5, 2, 7, 5, 8, 4, 6, 3, 2, 6, 4, 3, 7, 2, 8, 6, 6, 7, 4, 7, 5, 4, 7, 3, 4, 7, 7, 3, 5, 4, 6, 7, 9, 5, 8, 2, 4, 6, 11, 7, 9, 2, 3, 2, 6, 6, 7, 7, 5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7, 1, 8, 4, 6] # the mean = 5.44 # the mode = 5 # the median = 5 def mmm(numbers): """Return the mean, mode and median of a list of numbers""" # float is necessary as python2 does integer division... mean = float(sum(numbers))/len(numbers) # fill in a dictionary where the key is each value in n and count # the entries entries = dict() for i in numbers: if i in entries: # is there already this value entries[i] += 1 # increment it else: # if not create it entries[i] = 1 # set first value to 1 maxEntry = 0 mode = 0 # note need iteritems() below if using python2 for k,v in entries.items(): # k = key, i.e. number from n, v=value i.e. count of number if v > maxEntry: maxEntry = v mode = k nSort = numbers.copy() # must "deep copy" numbers to avoid changing # the list nSort.sort() median = nSort[int(len(nSort)/2)] # int as python3 does float # division... return mean,mode,median mean,mode,median = mmm(numbers) print("mean = {:5.3} mode = {} median = {}".format(mean,mode,median))