Jess
Jess

Reputation: 61

How to I assign each variable in a list, a number, and then add the numbers up for the same variables?

For example, if ZZAZAAZ is input, the sum of A would be 14 (since its placement is 3,5,6), while the sum of Z would be 14 (1 + 2 + 4 + 7).

How would I do that?

Upvotes: 4

Views: 88

Answers (3)

miradulo
miradulo

Reputation: 29720

Furthering Kasra's idea of using enumerate, if you wanted a dictionary containing these sums you could use a dictionary comprehension, and iterate over the set of unique characters, like so:

>>> s = 'ZZAZAAZ' 
>>> {let:sum(a for a,b in enumerate(s,1) if b==let) for let in set(s)}
{'Z': 14, 'A': 14}

Upvotes: 0

Saksham Varma
Saksham Varma

Reputation: 2140

For all the elements in s you could do this. Also, it would find the counts for each element in a single pass of the string s, hence it's linear in the number of elements in s.

>>> s = 'ZZAZAAZ'
>>> d = {}
>>> for i, item in enumerate(s):
    ... d[item] = d.get(item, 0) + i + 1
>>> print d
{'A': 14, 'Z': 14}

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

You can use a generator expression within sum :

>>> s='ZZAZAAZ'
>>> sum(i for i,j in enumerate(s,1) if j=='A')
14

Upvotes: 10

Related Questions