Write a program to determine the mean, median, and standard deviation of a list of numbers
Count the duplicate numbers in the code, listing any that occur more than once with the number of times it occurs.
My implementation:
import math
def mean(input):
return sum(input) / float(len(input))
def median(input):
sorted_input = sorted(input)
length = len(input)
if length < 1:
return None
if length % 2 == 0:
return (sorted_input[length / 2] + sorted_input[length / 2 - 1]) / float(2)
else:
return sorted_input[length / 2]
def duplicate_counts(input):
distinct_input = set(input)
for distinct in set(input):
count = input.count(distinct)
if (count > 1):
print("{} occurs {} times".format(distinct, count))
def standard_deviation(input):
return math.sqrt(mean([(x - mean(input)) ** 2 for x in input]))
def main():
#sample run/test
the_list = [3, 6, 7, 2, 8, 9, 2, 3, 7, 4, 5, 9, 2, 1, 6, 9, 6]
print("The mean is: {}".format(mean(the_list)))
print("The median is: {}".format(median(the_list)))
print("The standard deviation is: {}".format(standard_deviation(the_list)))
duplicate_counts(the_list)
if __name__ == "__main__":
main()
Sample output:
The mean is: 5.23529411765 The median is: 6 The standard deviation is: 2.64640514805 2 occurs 3 times 3 occurs 2 times 6 occurs 3 times 7 occurs 2 times 9 occurs 3 times
Simple exercise I decided to do with Python for practice and to test/try all the excellent feedback I received on my previous two questions. There may be built in functions for these, and feel free to mention them, but for the sake of practice I implemented them this way.