heights = [180, 172, 178, 185, 190, 195, 192, 200, 210, 190]
height_sum = sum(heights)
mean = height_sum / len(heights)
# **2 makes negatives (heights less than the mean) become positive.
diff_list = [(x - mean) ** 2 for x in heights]
variance = sum(diff_list) / len(heights)
# We get the square root in order to get back the original units.
standard_deviation = variance **0.5
# Now we just need to find out how many heights are within the
# standard deviation from the mean.
count = 0
upper_lim = mean + standard_deviation
lower_lim = mean - standard_deviation
# Count how many heights are within the
# standard deviation from the mean.
for height in heights:
if lower_lim < height < upper_lim:
count += 1
print(count)
''' Or as a class, initiated with the heights list: '''
class Std():
def __init__(self, data: list):
self.data = data
self.mean = self._get_mean()
self.var = self._get_variance()
self.std = self._get_std_from_var()
self.upper_lim = self.mean + self.std
self.lower_lim = self.mean - self.std
self.in_range = lambda x: self.lower_lim < x < self.upper_lim
self.count_within = len(list(filter(self.in_range, self.data)))
def _get_mean(self):
return sum(self.data) / len(self.data)
def _get_variance(self):
diff_list = [(x - self.mean) ** 2 for x in self.data]
return sum(diff_list) / len(diff_list)
def _get_std_from_var(self):
return self.var **0.5
std = Std(heights)
print(std.count_within)
Inga kommentarer:
Skicka en kommentar