Python Programming: An Introduction to Computer Science

(Nora) #1
184 CHAPTER11. DATA COLLECTIONS

def stdDev(nums, xbar):
sumDevSq = 0.0
for num in nums:
dev = num - xbar
sumDevSq = sumDevSq+ dev * dev
return sqrt(sumDevSq/(len(nums)-1))


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


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

if name == ’main’:main()


11.4 CombiningListsandClasses.


Inthelastchapter, wesaw how classescouldbeusedto structuredatabycombiningseveralinstancevariables
togetherintoa singleobject.Listsandclassesusedtogetherarepowerfultoolsforstructuringthedatainour
programs.
RemembertheDieViewclassfromlastchapter?Inordertodisplaythesixpossiblevaluesofa die,
eachDieViewobjectkeepstrackofsevencirclesrepresentingthepositionofpipsonthefaceofa die.In
thepreviousversion,wesavedthesecirclesusinginstancevariables,pip1,pip2,pip3, etc.
Let’s considerhow thecodelooksusinga collectionofcircleobjectsstoredasa list.Thebasicideais to
replaceourseveninstancevariableswitha singlelistcalledpips. Ourfirstproblemis totocreatea suitable
list.ThiswillbedoneintheconstructorfortheDieViewclass.
Inourpreviousversion,thepipswerecreatedwiththissequenceofstatementsinsideof init :


self.pip1 = self.makePip(cx-offset, cy-offset)
self.pip2 = self.
makePip(cx-offset, cy)
self.pip3 = self.makePip(cx-offset, cy+offset)
self.pip4 = self.
makePip(cx,cy)
self.pip5 = self.makePip(cx+offset, cy-offset)
self.pip6 = self.
makePip(cx+offset, cy)
self.pip7 = self.__makePip(cx+offset, cy+offset)


Recallthat makePipis a localmethodoftheDieViewclassthatcreatesa circlecenteredat thepostion
givenbyitsparameters.

Free download pdf