Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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?

like image 999
Jess Avatar asked Dec 20 '22 05:12

Jess


2 Answers

You can use a generator expression within sum :

>>> s='ZZAZAAZ'
>>> sum(i for i,j in enumerate(s,1) if j=='A')
14
like image 188
Mazdak Avatar answered Dec 22 '22 00:12

Mazdak


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}
like image 34
Saksham Varma Avatar answered Dec 22 '22 01:12

Saksham Varma