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?
You can use a generator expression within sum
:
>>> s='ZZAZAAZ'
>>> sum(i for i,j in enumerate(s,1) if j=='A')
14
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With