Python: Use the file table.txt , found in the web address below. Copy and paste
ID: 3602518 • Letter: P
Question
Python: Use the file table.txt, found in the web address below. Copy and paste the web address into your web browser to view list of numbers. The program should look for its input data in the file table.txt.
https://instructure-uploads.s3.amazonaws.com/account_18600000000000001/attachments/2490162/table.txt?response-content-disposition=inline%3B%20filename%3D%22table.txt%22%3B%20filename%2A%3DUTF-8%27%27table.txt&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJFNFXH2V2O7RPCAA%2F20171026%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20171026T234128Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=f397520289b2944a102a6be1eac8446af74c6f6849fc0a6ac2ac019c643dc172
Write functions mymean(x), mystd(x), and mycor (x, y) that will return the mean of a list x, the standard deviation of a list x, and the correlation by the lists x and y Using the file table.txt, assign the first column of data to x and the third column to y. Then find the mean and standard deviation of x, the mean and standard deviation of y, and the correlation between x and y using the functions mymean, mystd, and mycorExplanation / Answer
Install numpy module to run below program
import numpy
def mymean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/n # in Python 2 use sum(data)/float(n)
def _ss(data):
"""Return sum of square deviations of sequence data."""
c = mymean(data)
ss = sum((x-c)**2 for x in data)
return ss
def mystd(data, ddof=0):
#Calculates the population standard deviation by default; specify ddof=1 to compute the sample standard deviation.
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/(n-ddof)
return pvar**0.5
def mycor(x,y):
return numpy.corrcoef(x,y)
a=[]
b=[]
with open("table.txt", "r") as datafile:
a.extend(datafile.read().split()[0::3])
with open("table.txt", "r") as datafile:
b.extend(datafile.read().split()[2::3])
x= list(map(int, a))
y= list(map(int, b))
print("mean of x",mymean(x))
print("mean of y",mymean(y))
print("standard deviation of x",mystd(x))
print("standard deviation of y",mystd(y))
# print(x)
# print(y)
print("correlation between x and y ",mycor(x,y))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.