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.
def count_letters(text): result = {} counter = 0 # Go through each letter in the text for letter in text: if letter.islower() or letter.isupper(): # Check if the letter needs to be counted or not if letter not in result: counter = 0 # Add or increment the value in the dictionary counter += 1 result[letter.lower()] = counter return result print(count_letters("This is a sentence.")) # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
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:
{'t': 2, 'h': 1, 'i': 2, 's': 2, 'a': 1, 'e': 2, 'n': 4, 'c': 1}
Advertisement
Answer
def count_letters(text): result = {} counter = 0 # Go through each letter in the text for letter in text: if letter.islower() or letter.isupper(): # Check if the letter needs to be counted or not if letter not in result: counter = 0 # Add or increment the value in the dictionary counter += 1 result[letter.lower()] = counter return result print(count_letters("This is a sentence."))
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
.
def count_letters(text): result = {} # Go through each letter in the text for letter in text: if letter.islower() or letter.isupper(): # Check if the letter needs to be counted or not if letter not in result: result[letter.lower()] = 0 # Add or increment the value in the dictionary result[letter.lower()] += 1 return result print(count_letters("This is a sentence."))
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