-4
\$\begingroup\$

I have a requirement to get incremental counts. I am new to Python so please help me.

I have tried below:

Testword = 'foo boo'
letters = 'abcdefghijklmnopqrstuvwxyz'
for key in Testword:
    print key, Testword.count(key)

Results :

f 1
o 4
o 4
  1
b 1
o 4
o 4

I would like to get incremented count output in the same input order like

f=1
o=1
o=2

b=1
o=3
o=4

Please help me.

\$\endgroup\$
1
\$\begingroup\$

What you are looking for is the number of occurences until the position, you are currently looking at. Using Testword[:pos+1], you can take the substring until the current position. Hence:

testword = 'foo boo'
letters = 'abcdefghijklmnopqrstuvwxyz'
for pos, key in enumerate(testword):
    print(key, testword[:pos+1].count(key))

Gives

f 1
o 1
o 2
  1
b 1
o 3
o 4

Btw, please use python3, not python2.

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ Please note, questions involving code that's not working as intended are off-topic on this site and should not be answered. If OP edits their post to address the problem and makes their post on-topic, they may make your answer moot. Anyways, on-topic questions get more views and will get you more rep in the long run ;) See this meta discussion for reference: codereview.meta.stackexchange.com/q/6604/98493 \$\endgroup\$ – Graipher Apr 20 '18 at 12:49
  • \$\begingroup\$ This code could do with a Code Review, to remove the \$n^2\$ complexity. \$\endgroup\$ – Peilonrayz Apr 20 '18 at 15:51

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