Working with a list in a more "pythonic" way

Terry Reedy tjreedy at udel.edu
Sun Apr 4 15:57:00 EDT 2004


"Nickolay Kolev" <nmkolev at uni-bonn.de> wrote in message
news:20040404124833458+0200 at news.rhrz.uni-bonn.de...
> I would like to find a more pythonic way of solving the following:
...
> I have come up with the following solution, but I hope some of you might
> suggest a more _functional_ (reduce and map) way of diong it.

For anti-reduce Pythoneers, those two desires are contradictory;-)  My
take: Pythonic is first correct, then about as clear as possible what is
being done and why that gives the correct answer.  Both your table lookup
and Daniels dict lookup are immediately obvious and thus qualify to me.
Both handle the switch between chars and pairs of chars about as smoothly
as possible (except for your unnecessary try: except: as a substitute for
subtracting 1 from the length).

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.

Terry J. Reedy







More information about the Python-list mailing list