Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I've created these 3 functions to count the value of letters in a word.

All these functions are functionally the same.

Apparently List comprehensions (count_word3) are usually seen as the most pythonic in these situations. But to me it is the least clear of the 3 examples.

Have I stumbled across something that is so simple that lambdas are acceptable here or is "the right thing to do" to use the list comprehension?

Or is there something better?

def count_word1(w):
    def count(i, a):
        return i + ord(a) - 64
    return reduce(count, w, 0)

def count_word2(w):
    return reduce(lambda a,b : a + ord(b) - 64, w, 0)

def count_word3(w):
    vals = [ord(c) - 64 for c in w]
    return sum(vals)
share|improve this question

2 Answers

up vote 3 down vote accepted

how's example 3 the least readable? I would write it a little better but you've got it right already:

def count_word3(word): 
    return sum(ord(c) - 64 for c in word) 
share|improve this answer
I've probably just done too much scala :-). I'm just asking for opinions from the python community to refine my python style. – andy boot Jul 20 '12 at 13:10

These are the most readable for me:

sum((ord(letter) - ord('A') + 1) for letter in word)

Or

def letter_value(letter):
    return ord(letter) - ord('A') + 1

sum(map(letter_value, word))

btw, the code might break for non-ASCII strings.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.