0

I have a list of names:

names = ['ALICE', 'BOB', 'ME']

Take 'A' as 1, 'B' as 2, 'C' as 3... The sum of 'ALICE' can be calculated with:

sum([ord(i) - ord('A') + 1 for i in 'ALICE'])  // ALICE: 30, BOB: 19, ME: 18

Now, I want to calculate all the sum in names multiplied with index in the names, e.g., 30 * 1 + 19 * 2 + 18 * 3 = 122.

It's easy to do this like:

s = 0
for i in range(len(names)):
    s += sum(([ord(j) - ord('A') + 1) * (i + 1) for j in names[i]])
print s

But I want to learn to do this in list generator style (in one line perhaps). How to do this?

1 Answer 1

3

Using enumerate:

>>> names = ['ALICE', 'BOB', 'ME']
>>> sum(i * sum(ord(ch) - ord('A') + 1 for ch in name) for i, name in enumerate(names, 1))
122

sum accepts any iterable, so you can pass generator expression instead of list comprehension.


>>> enumerate('ALICE')
<enumerate object at 0x7f8f7b8c42d0>
>>> list(enumerate('ALICE'))
[(0, 'A'), (1, 'L'), (2, 'I'), (3, 'C'), (4, 'E')]
>>> list(enumerate('ALICE', 1))
[(1, 'A'), (2, 'L'), (3, 'I'), (4, 'C'), (5, 'E')]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.