Working with a list in a more "pythonic" way
Terry Reedy
tjreedy at udel.edu
Mon Apr 5 02:44:55 EDT 2004
"David Eppstein" <eppstein at ics.uci.edu> wrote in message
news:eppstein-78D3D6.14092304042004 at news.service.uci.edu...
> 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?
In order to use sum(), one must have the items to be summed. The OP does
not have them but must generate them in a explicit loop. At that point, it
seems sensible to me to directly add them instead of yielding or collecting
them to be summed in a second (or third) loop in the sum function.
> I also don't like seeing the magic number 65
> without some sort of explanation.
Agreed. Something for the OP to add.
> And how come you're using x in one place and phrase in another?
I cut and pasted. Obvious, OP needs to use one or the other.
> 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])
Terry J. Reedy
More information about the Python-list
mailing list