# computes the average (mean), the median, and the standard deviation of # a sequence of numbers from a file from math import sqrt def readData(source): """ source is a reference to opened file, numbers in the file should be separated by white space or next line, returns the list of values""" result = [] for line in source: nums = line.split() # splitting by white space for item in nums: try: result.append(float(item)) except: print("Warning: non-numerical value located, ignored") result.sort() return result def getMean(listOfVals): """ returns the mean/average of values in the list listOfVals """ return sum(listOfVals)/len(listOfVals) def getMedian(listOfVals): """ returns the middle element of the list listOfVals if odd number of elements, and the average of two middle elements if even number of elements """ n =len(listOfVals) if n % 2 == 0: return (listOfVals[n//2] + listOfVals[n//2 - 1])/2 else: return listOfVals[n//2] def getS(vals): """ returns the standard deviation of the list of values vals """ mean = getMean(vals) s = 0 for value in vals: s += (mean - value)**2 return sqrt( s / (len(vals) - 1) ) def main(): fname = input("Enter the file name:") source = open(fname) listOfValues = readData(source) mean = getMean(listOfValues) median = getMedian(listOfValues) standardDeviation = getS(listOfValues) print("Here are the values read from file:") for item in listOfValues: print(item, end=", ") print() print("Their mean(average) is ",mean,", ") print("their median is ",median,", and") print("their standard deviation is ",standardDeviation) main()