-2

Given the next word:

ABCABACBABACACBACBAC

What would be the most efficient way to count the letters that appear in the word using python?

(Solution: A:8, B:6, C:6)

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Sergio
  • 63
  • 5

2 Answers2

1

Don't reinvent the wheel - just use a Counter:

from collections import Counter
result = Counter('ABCABACBABACACBACBAC')
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You can solve it like this:

>>> def counter(in_str):
...     out_dict = dict()
...     for char in in_str:
...             if char in out_dict:
...                     out_dict[char] += 1
...             else:
...                     out_dict[char] = 1
...     return out_dict
... 
>>> counter("ABCABACBABACACBACBAC")
{'A': 8, 'B': 6, 'C': 6}
>>> 

If you want to give a try on how to implement things.

Cardstdani
  • 4,999
  • 3
  • 12
  • 31
Kunal Sharma
  • 416
  • 3
  • 12
  • You could do for instance `out_dict[char] = out_dict.get(char, 0) + 1` to avoid the `if/else`. But there is already `collections.Counter`, a subclass of `dict` which does all that and is probably more optimised, so there is no need to implement your own function. – Stef Nov 01 '21 at 19:24