Skip to content
Advertisement

Some letters are not getting counted in the below code in Python

I am trying to write a code to count letters in a string and store them as key value pair in a separate dictionary with key as the letter and value as the total count of that respective letter.

JavaScript

Could anyone please help me out what is going wrong in the code as I am not able to debug it.

I am getting Output as below:

JavaScript

Advertisement

Answer

JavaScript

In your code the problem is with counter variable. As it resets its value if new letter come in result dict and does not store the count for previous letters.

Counter in your code is working like this:

  • loop letter counter
  • 1 T 1
  • 2 h 1
  • 3 i 1
  • 4 s 1
  • 5 i 2
  • 6 s 2
  • 7 a 1
  • 8 s 2 – remain same here as 6 line
  • 9 e 1
  • 10 n 1
  • 11 t 2
  • 12 e 3
  • 13 n 4
  • 14 c 1
  • 15 e 2

Above problem could be solved by directly making changes in the dictionary rather then using any another variable

.

JavaScript

Here the output: {‘t’: 2, ‘h’: 1, ‘i’: 2, ‘s’: 3, ‘a’: 1, ‘e’: 3, ‘n’: 2, ‘c’: 1}

I hope it clear your doubt

Advertisement