11.3. STATISTICSWITHLISTS 183
def median(nums):
nums.sort()
size = len(nums)
midPos = size / 2
if size % 2 == 0:
median = (nums[midPos]+ nums[midPos-1]) / 2.0
else:
median = nums[midPos]
return median
Youshouldstudythiscodecarefullytobesureyouunderstandhowit selectsthecorrectmedianfromthe
sortedlist.
Themiddlepositionofthelistis calculatedusingintegerdivisionassize / 2. Ifsizeis 3,then
midPosis 1 (2goesinto3 justonetime).Thisis thecorrectmiddleposition,sincethethreevaluesinthe
listwillhave theindexes0,1,2. Nowsupposesizeis 4. Inthiscase,midPoswillbe2,andthefour
valueswillbeinlocations0, 1, 2, 3.Thecorrectmedianis foundbyaveragingthevaluesatmidPos(2)and
midPos-1(1).
Now thatwehave allthebasicfunctions,finishingouttheprogramis a cinch.
def main():
print ’This programcomputes mean, median and standard deviation.’
data = getNumbers()
xbar = mean(data)
std = stdDev(data,xbar)
med = median(data)
print ’\nThe meanis’, xbar
print ’The standarddeviation is’, std
print ’The medianis’, med
Many computationaltasksfromassigninggradesto monitoringflightsystemsonthespaceshuttlerequire
somesortofstatisiticalanalysis.Byusingtheif name == ’ main ’technique,wecanmake our
codeusefulasa stand-aloneprogramandasa generalstatisticallibrarymodule.
Here’s thecompleteprogram:
stats.py
from math import sqrt
def getNumbers():
nums = [] # startwith an empty list
# sentinel loopto get numbers
xStr = raw_input("Entera number (<Enter> to quit) >> ")
while xStr != "":
x = eval(xStr)
nums.append(x) # add this value to the list
xStr = raw_input("Entera number (<Enter> to quit) >> ")
return nums
def mean(nums):
sum = 0.0
for num in nums:
sum = sum + num
return sum / len(nums)