Python Programming: An Introduction to Computer Science

(Nora) #1
178 CHAPTER11. DATA COLLECTIONS

Supposewewanttoextendthisprogramsothatit computesnotonlythemean,butalsothemedianand
standard deviationofthedata.Youareprobablyfamiliarwiththeconceptofa median.Thisis thevaluethat
splitsthedatasetintoequal-sizedparts.Forthedata2,4, 6,9, 13,themedianvalueis 6,sincetherearetwo
valuesgreaterthan6 andtwo thataresmaller. To calculatethemedian,weneedtostoreallthenumbersand
puttheminordersothatwecanidentifythemiddlevalue.
Thestandarddeviationisa measureofhowspreadoutthedataisrelative tothemean. Ifthedatais
tightlyclusteredaroundthemean,thenthestandarddeviationis small.Whenthedatais morespreadout,the
standarddeviationis larger. Thestandarddeviationprovidesa yardstickfordetermininghow exceptionala
valueis.Forexample,someteachersdefinean“A” asany scorethatis at leasttwo standarddeviationsabove
themean.
Thestandarddeviation,s, is definedas


s




̄x xi^2
n 1

Inthisformula ̄xis themean,xirepresentstheithdatavalueandnis thenumberofdatavalues.Theformula
lookscomplicated,butit is nothardtocompute.Theexpression


̄x xi^2 is thesquareofthe“deviation”of
anindividualitemfromthemean.Thenumeratorofthefractionis thesumofthedeviations(squared)across
allthedatavalues.
Let’s take a simpleexample.If weagainusethevalues:2, 4, 6, 9, and13,themeanofthisdata( ̄x) is 6.8.
Sothenumeratorofthefractionis computedas


6 8  2 ^2 



6 8  4 ^2 


6 8  6 ^2 


6 8  9 ^2 


6 8  13 ^2 149 6

Finishingoutthecalculationgivesus


s


149 6
5  1



37 4 6 11

Thestandarddeviationis about6.1.Youcanseehowthefirststepofthiscalculationusesboththemean
(whichcan’t becomputeduntilallofthenumbershave beenentered)andeachindividualvalueaswell.
Again,thisrequiressomemethodtorememberalloftheindividualvaluesthatwereentered.


11.2 ApplyingLists


Inordertocompleteourenhancedstatisticsprogram,weneeda waytostoreandmanipulateanentire
collectionofnumbers.We can’t justusea bunchofindependentvariables,becausewedon’t know how many
numberstherewillbe.
Whatweneedis somewayofcombininganentirecollectionofvaluesintooneobject.Actually, we’ve
alreadydonesomethinglike this,butwehaven’t discussedthedetails. Take a lookattheseinteractive
examples.





range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
string.split("This is an ex-parrot!")
[’This’, ’is’, ’an’,’ex-parrot!’]





Bothofthesefamiliarfunctionsreturna collectionofvaluesdenotedbytheenclosingsquarebrackets.As
youknow, thesecollectionsarecalledlists.


11.2.1 ListsareSequences.


Listsareorderedsequencesofitems.Theideasandnotationsthatweuseformanipulatinglistsareborrowed
frommathematics.Mathematicianssometimesgive anentiresequenceofitemsa singlename.Forinstance,
a sequenceofnnumbersmightjustbecalledS:


S s 0 s 1 s 2 s 3 sn 1
Free download pdf