Working with a list in a more ?pythonic? way
Carl Banks
imbosol at aerojockey.invalid
Sun Apr 4 20:14:58 EDT 2004
Nickolay Kolev wrote:
> 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.
>
> 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
>
> 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).
IMO, the clearest functional way to do it (where, for the sake of
argument, we're defining functional not to include list comps) is to
use offset slices. The idea is to use one slice of phrase to
represent the first index, and a second slice, offset by one, to
represent the second index in the matrix. I'd also map the phrase
into integers beforehand. Take a look:
iphrase = map(lambda x:ord(x)-65,phrase)
n = sum(map(lambda a,b: soundScoreMatrix[a][b], iphrase[:-1], iphrase[1:]))
If you want to use reduce instead of sum (say you're not yet at Python
2.3), then replace "sum(x)" with "reduce(operator.add,x)".
--
CARL BANKS http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
-- Parody of Mr. T from a Robert Smigel Cartoon
More information about the Python-list
mailing list