-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\$

closed as off-topic by Peilonrayz, t3chb0t, Toby Speight, alecxe, Graipher Apr 20 '18 at 12:47

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – Peilonrayz, t3chb0t, Toby Speight, alecxe, Graipher
If this question can be reworded to fit the rules in the help center, please edit the question.

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.

\$\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.