Math & Physics Problems Wikia
Advertisement

By: Tao Steven Zheng (郑涛)

Statistics.jpg

Code

 1 def statistics(samples):
 2 
 3     N = len(samples)
 4     mean = sum(samples) / N
 5     sum_squares = sum((mean-x)**2 for x in samples)
 6     stan_dev = (sum_squares/(N-1))**0.5
 7     
 8     if N % 2 == 1:
 9         median =  sorted(samples)[N//2]  #odd case for median
10     if N % 2 == 0:
11         median = sum(sorted(samples)[N//2-1:N//2 + 1]) / 2 #even case for median
12 
13     minimum = min(samples)
14     maximum = max(samples)
15     data_range = maximum - minimum
16     
17     print("Mean:", mean)
18     print("Standard Deviation:", stan_dev)
19     print("Minimum:", minimum)
20     print("Median:", median)
21     print("Maximum:", maximum)
22     print("Data range:", data_range)
23     print("Sample Size:", N)


Tests

samples = [1,2,3,4,5,6]

statistics(samples)

Results

Mean: 3.5
Standard Deviation: 1.8708286933869707
Minimum: 1
Median: 3.5
Maximum: 6
Data range: 5
Sample Size: 6
Advertisement