HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Statistics with Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withstatisticspython

Problem

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):
      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.

Solution

-
A variable name input is confusing. After all, input is a Python built-in.

-
standard_deviation calls mean too many times (add a debug printout to mean to see). Better do

def standard_deviation(input):
    input_mean = mean(input)
    return math.sqrt(mean([(x - input_mean) ** 2 for x in input]))


-
Median can be calculated in \$ O(\log n)\$. Sorting a list in \$O(n \log n)\$ just for a median is an overkill.

Code Snippets

def standard_deviation(input):
    input_mean = mean(input)
    return math.sqrt(mean([(x - input_mean) ** 2 for x in input]))

Context

StackExchange Code Review Q#108840, answer score: 5

Revisions (0)

No revisions yet.