-1

I have been challenged to find a way to count how often a letter occurs in a text. I am not allowed to use any modules (import) and the .count function.

Example:

text = 'hello'

How can I check how often each letter occurs in the variable text? How would a beginner do this? Maybe by using a function.

The final result should look like this:

h: 1, e: 1, l: 2, o: 1

Thanks in advance.

Leroy
  • 9
  • 5

1 Answers1

0

You can use a dictionary. The keys are the characters found and values are the count.

>>> counts = {}
>>> for c in text:
...     if c not in counts:
...             counts[c] = 1
...     else:
...             counts[c] += 1
... 
>>> counts
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Use dict.get() to clean your code. Use `counts[letter] = counts.get(letter, 0)+1` instead of what you wrote in your loop. – Behzad Shayegh Jan 24 '21 at 16:46
  • @BehzadShayegh - that's a good alternative, but personally I like the if/else form which I find easier to visualize. But that's just eye of the beholder, perhaps. – tdelaney Jan 24 '21 at 16:47