Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1 #write a function called st dev. st dev should have one 2 #parameter, a filena

ID: 3708511 • Letter: 1

Question

1 #write a function called st dev. st dev should have one 2 #parameter, a filename. The file will contain one integer on 3 #each line. The function should return the population standard 4 #deviation of those numbers. 5# 6 #The formula for population standard deviation can be found here: 7 #edge .edx.org/asset-v1:GTxtgt-mooc-staging 1+2018 TI-type@asset-block@stdev . PNG 8# 9 #The formula is a bit complex, though , and since this is a 10 #cs class and not a math class, here are the steps you would 11 #take to calculate it manually: 12 # 13 # 1 . Find the mean of the list. 14 # 2 . For each data point, find the difference between that 15 # 16 # 17 # 4. Divide the sum of differences by the length of the 18 # 19 # 5. Take the sguare root of the result. 20 #You may assume for this problem that the file will contain 21 #only integers-you don't need to worry about invalid 22 #files or lines. The easiest way to take the square root is 23 #to raise it to the 0.5 power (e.g. 2 ** 0.5 will give the 24 #Square root of 2). 25 # 26 #HINT: You might find this easier if you load all of the 27 #numbers into a list before trying to calculate the average 28 #Either way, you're going to need to loop over the numbers 29 #at least twice: once to calculate the mean, once to 30 #calculate the sum of the differences. 31 #Add your function here! 32 point and the mean. Square that difference, and add it to a running sum of differences. list. 34 35 #Below are some lines of code that will test your function. 36 #You can change the value of the variable (s) to test your 37 #function with different inputs. 38 # 39 #If your function works correctly, this will originally 40 #print 27.796382658340438 (or something around there). 41 print(st dev( "some numbers.txt"

Explanation / Answer

import math

def st_dev(filename):

    # open file in read mode

    fptr = open(filename , 'r')

   

    # read the file content and save into x

    a = fptr.read()

   

    # create a list of all the entries in file

    # map() applies the function passed as first argument to each element in the second argument

    # list() return a list of all elements passed as arguments

    arr = list( map( int , a.split(' ') ) )

   

    sum = 0

   

    # calculate the sum of all elements in arr

    for x in arr:

   

        sum += x

       

    # calculate mean

    mean = sum / len(arr)

   

    # store the standard deviation

    sd = 0

   

    for x in arr:

   

        sd += math.pow( x - mean , 2 )

       

    sd = sd / len(arr)

   

    sd = math.sqrt( sd )

   

    return sd

   

print(st_dev('some_numbers.txt'))

----------------------some_numbers.txt---------------------

23
45
65
12
1
4
54
87
56
32
12

Sample Output

26.68115997329691