Working with a list in a more "pythonic" way

David Eppstein eppstein at ics.uci.edu
Sun Apr 4 18:09:23 EDT 2004


In article <mailman.338.1081108625.20120.python-list at python.org>,
 "Terry Reedy" <tjreedy at udel.edu> wrote:

> Rewritten, your code is
> 
> score = 0
> for i in range(len(phrase)-1):
>     score += soundScoreMatrix[ord(x[i]) - 65][ord(x[i + 1]) - 65]
> 
> Once written thusly, the reduce form is obvious (but obviously not tested):
> 
> reduce(lambda score, i: score + soundScoreMatrix[ord(x[i]) - 65][ord(x[i +
> 1]) - 65],
>              range(len(phrase)-1), 0)
> 
> but aside from any didactic value this has, I prefer, in this case, the
> written-out loop.

I prefer the sum form -- if sum() isn't good for this example, what is 
it there for at all?  I also don't like seeing the magic number 65 
without some sort of explanation.  And how come you're using x in one 
place and phrase in another?

ords = [ord(c) - ord('A') for c in phrase.upper()]
score = sum([soundScoreMatrix[ords[i]][ords[i+1]]
             for i in range(len(phrase)-1)
             if 0 <= ords[i] < 26 and 0 <= ords[i+1] < 26])

-- 
David Eppstein                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science



More information about the Python-list mailing list