LAB-3
Part A
Read N numbers from the console and create a list. Develop a program and
standard deviation with suitable print mean, variance messages.
import math
def mean(data):
n = len(data)
mean_val = sum(data) / n
return mean_val
def variance(data):
n = len(data)
mean_val = mean(data)
deviations = [(x - mean_val) ** 2 for x in data]
variance_val = sum(deviations) / n
return variance_val
def stdev(data):
var = variance(data)
std_dev = math.sqrt(var)
return std_dev
listA = []
n = int(input("Enter the number of elements: "))
for i in range(n):
element = int(input("Enter element {}: ".format(i+1)))
listA.append(element)
print("List:", listA)
print("Mean of the sample is %s" % (mean(listA)))
print("Variance of the sample is %s" % (variance(listA)))
print("Standard Deviation of the sample is %s" % (stdev(listA)))
Output:
Enter the number of elements: 4
Enter element 1: 2
Enter element 2: 4
Enter element 3: 6
Enter element 4: 8
List: [2, 4, 6, 8]
Mean of the sample is 5.0
Variance of the sample is 5.0
Standard Deviation of the sample is 2.23606797749979
From lab manual
import math
def mean(data):
n = len(data)
mean_val = sum(data) / n
return mean_val
def variance(data):
n = len(data)
mean_val = mean(data)
deviations = [(x - mean_val) ** 2 for x in data]
variance_val = sum(deviations) / n
return variance_val
def stdev(data):
var = variance(data)
std_dev = math.sqrt(var)
return std_dev
listA = []
n = int(input("Enter the number of elements: "))
for i in range(n):
element = int(input())
listA.append(element)
print("List:", listA)
print("Mean of the sample is %s" % (mean(listA)))
print("Variance of the sample is %s" % (variance(listA)))
print("Standard Deviation of the sample is %s" % (stdev(listA)))
Algorithm:
1. Start
2. Initialize an empty list listA.
3. Input the number of elements n.
4. Repeat the following steps n times:
• Prompt the user to input a number.
• Append the number to listA.
5. Define Function mean(data):
• Calculate the number of elements n in data.
• Compute the mean as sum of data / n.
• Return the mean.
6. Define Function variance(data):
• Calculate the number of elements n in data.
• Call mean(data) to compute the mean.
• For each element x in data, compute the squared deviation from the mean: (x -
mean)^2.
• Compute the variance as the sum of squared deviations divided by n.
• Return the variance.
7. Define Function stdev(data):
• Call variance(data) to compute the variance.
• Compute the square root of the variance.
• Return the standard deviation.
8. Display the original list listA.
9. Call and display the result of mean(listA).
10.Call and display the result of variance(listA).
11.Call and display the result of stdev(listA).
12.End
Output:
Enter the number of elements: 4
2
4
6
8
List: [2, 4, 6, 8]
Mean of the sample is 5.0
Variance of the sample is 5.0
Standard Deviation of the sample is 2.23606797749979