Python Programming: An Introduction to Computer Science
11.6. NON-SEQUENTIALCOLLECTIONS 193 Noticeespeciallytheveryendoftheprogram.To runtheapplication,wecreateaninstanceoftheCalculato ...
194 CHAPTER11. DATA COLLECTIONS 11.6.2 DictionaryOperations Like lists,Pythondictionariessupporta numberofhandybuilt-inoperation ...
11.6. NON-SEQUENTIALCOLLECTIONS 195 Atthehighestlevel,thisis justa multi-accumulatorproblem.We needa countforeachwordthatappears ...
196 CHAPTER11. DATA COLLECTIONS counts = {} for w in words: try: counts[w]= counts[w] + 1 except KeyError: counts[w]= 1 Ourlasts ...
11.6. NON-SEQUENTIALCOLLECTIONS 197 return cmp(w1,w2) else: return 1 Thisfunctionacceptstwo parameters,eachofwhichis a tupleoftw ...
198 CHAPTER11. DATA COLLECTIONS counts = {} for w in words: try: counts[w]= counts[w] + 1 except KeyError: counts[w]= 1 # output ...
11.7. EXERCISES 199 (a)s1 + s2 (b)3 * s1 + 2 * s2 (c)s1[1] (d)s1[1:3] (e)s1 + s2[-1] Giventhesameinitialstatementsasintheprevio ...
200 CHAPTER11. DATA COLLECTIONS Set(elements)Createa set(elementsis theinitiallistofitemsintheset). addElement(x)Addsxtotheset. ...
Chapter 12 Object-Oriented Design Nowthatyouknowsomedatastructuringtechniques,it’s timetostretchyourwingsandreallyputthose tools ...
202 CHAPTER12. OBJECT-ORIENTEDDESIGN importantcandidatesforobjects.Thingsthatseemtoinvolve a groupingofrelateddataitems(e.g., co ...
12.2. CASESTUDY: RACQUETBALLSIMULATION 203 12.2.1 CandidateObjectsandMethods Ourfirsttaskis tofinda setofobjectsthatcouldbeusefu ...
204 CHAPTER12. OBJECT-ORIENTEDDESIGN class SimStats: def init(self): self.winsA= 0 self.winsB= 0 self.shutsA= 0 self.shutsB= 0 N ...
12.2. CASESTUDY: RACQUETBALLSIMULATION 205 To finishouttheclass,weimplementtheprintLinemethod. Thismethodwillmake heavyuseof str ...
206 CHAPTER12. OBJECT-ORIENTEDDESIGN playerB: RBallGame server: playerA:playerA: Player prob: score: Player prob: score: 0 0.6 0 ...
12.2. CASESTUDY: RACQUETBALLSIMULATION 207 12.2.4 ImplementingPlayer IndevelopingtheRBallGameclass,wediscoveredtheneedforaPlayer ...
208 CHAPTER12. OBJECT-ORIENTEDDESIGN def incScore(self): # Add a pointto this player’s score self.score= self.score + 1 def getS ...
12.2. CASESTUDY: RACQUETBALLSIMULATION 209 def update(self,aGame): # Determinethe outcome of aGame and update statistics a, b = ...
210 CHAPTER12. OBJECT-ORIENTEDDESIGN theGame.play() # play it stats.update(theGame) # get info about completedgame # Print the r ...
12.3. CASESTUDY: DICEPOKER 211 constructorCreatetheinitialcollection. rollAllAssignrandomvaluestoeachofthefive dice. rollAssigna ...
212 CHAPTER12. OBJECT-ORIENTEDDESIGN def rollAll(self): self.roll(range(5)) I usedrange(5)togeneratea listofalltheindexes. Theva ...
«
5
6
7
8
9
10
11
12
13
14
»
Free download pdf