Working with a list in a more ?pythonic? way

Peter Otten __peter__ at web.de
Sun Apr 4 10:23:40 EDT 2004


Nickolay Kolev wrote:

> I was thinking about using "reduce", but that would not work as the
> input and output of the function I would use are different (string input,
> integer output).

reduce() does not impose such a restriction. Optimized for minimal
robustness and readability (but working, I hope, and functional in the
_narrow_ sense):

def calcScore(phrase):
    return reduce(
        lambda (sigma, last), i: (sigma + soundScoreMatrix[last][i], i),
        map(lambda c: ord(c)-65, phrase[1:]), (0, ord(phrase[0])-65))[0]

Seriously, trying to apply a particular style does often result in bad
design. Either go with Scott Daniels' approach or debug your initial idea
to something that works. Both ways are more "pythonic" than the above.

Peter





More information about the Python-list mailing list