62.2k views
2 votes
For this problem, you will write a function standard_deviation that takes a list whose elements are numbers (they may be floats or ints), and returns their standard deviation, a single number. You may call the variance method defined above (which makes this problem easy), and you may use sqrt from the math library, which we have already imported for you. Passing an empty list to standard_deviation should result in a ZeroDivisionError exception being raised, although you should not have to explicitly raise it yourself.

1 Answer

3 votes

Answer:

  1. import math
  2. def standard_deviation(aList):
  3. sum = 0
  4. for x in aList:
  5. sum += x
  6. mean = sum / float(len(aList))
  7. sumDe = 0
  8. for x in aList:
  9. sumDe += (x - mean) * (x - mean)
  10. variance = sumDe / float(len(aList))
  11. SD = math.sqrt(variance)
  12. return SD
  13. print(standard_deviation([3,6, 7, 9, 12, 17]))

Step-by-step explanation:

The solution code is written in Python 3.

Firstly, we need to import math module (Line 1).

Next, create a function standard_deviation that takes one input parameter, which is a list (Line 3). In the function, calculate the mean for the value in the input list (Line 4-8). Next, use the mean to calculate the variance (Line 10-15). Next, use sqrt method from math module to get the square root of variance and this will result in standard deviation (Line 16). At last, return the standard deviation (Line 18).

We can test the function using a sample list (Line 20) and we shall get 4.509249752822894

If we pass an empty list, a ZeroDivisionError exception will be raised.

User Chris J Harris
by
4.8k points