Working with a list in a more „pythonic“ way

Scott David Daniels Scott.Daniels at Acm.Org
Sun Apr 4 09:02:59 EDT 2004


Nickolay Kolev wrote:
> ...The sum of transition scores between the characters in a string.
 > The transition scores are stored in a 26 x 26 matrix. I.e. the
 > transition A -> F would have the score soundScoreMatrix[0][5].

This is the part I'd change:

     # Setup: transitionScore['AF'] = soundScoreMatrix[0][5].
     transitionScore = {}
     for i in range(26):
         first = chr(65+i)
         row = soundScoreMatrix[i]
         for j in range(26):
             transitionScore[first + chr(65+j)] = row[j]

> n = 0           # the final score of the string
> for i in range(len(phrase)):
> 	try:
> 		n += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65]
> 	except IndexError:
> 		pass

     def scoreit(phrase):
         score = 0
         for i in range(len(phrase) - 1):
             score += transitionScore.get(phrase[i : i+2], 0)
         return score

But if you insist on a more functional style:

     def scoreterse(phrase):
         return sum([transitionScore.get(phrase[i : i+2], 0)
                     for i in range(len(phrase) - 1)])

which doesn't really look clearer to me.  I'd be tempted to insert
a line:
         phrase = phrase.upper()

at the top of the function (scoreit or scoreterse) you use, depending,
of course, on the reliability of the source of your data.

-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list