[Tutor] another newbie question

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 11 Jul 2000 01:57:40 +0200


On Tue, Jul 11, 2000 at 08:37:14AM +0900, David Jansen wrote:
> 
> In A. Gauld's document.py (a copy of which is posted at
> http://www.sky.sannet.ne.jp/si75/document.py) in his Learning to Program
> tutorial there is the following function:
> 
> def generateStats(self):
> >>>>self.c_words = len(self.groups)
> >>>>sentences, clauses = 0, 0
> >>>>for c in self.stop_tokens:
> >>>>>>>>sentences = sentences + self.c_punctuation[c]
> >>>>self.c_sentence = sentences
> >>>>for c in self.c_punctuation.keys():
> >>>>>>>>clauses = clauses + self.c_punctuation[c]
> >>>>self.c_clause = clauses
> 
> Now my question is why it is necessary to add the sentences = sentences +...
> and clauses = clauses +... lines? Why not just:
> 
> self.c_sentence = self.c_sentence + self.c_punctuation[c]
> 
> and
> 
> self.c_clause = self.c_clause + self.c_punctuation[c]

Yes, that will work too. It's mostly a matter of style. It's cleaner to use
a local variable for the computation and only set the result in the instance
variable. c_sentence holds the count of sentences, period. It never holds
any intermediate results. Don't use one variable for two different things,
if you need to keep temporary results, use a temporary variable.

Also, if there are lots of tokens, using a local variable is slightly faster
than an instance variable inside the loop (it saves a lookup).

But it's not "necessary" to do it this way, no.

-- 
Remco Gerlich,  scarblac@pino.selwerd.nl