I'm trying to write a program that takes a string as input and counts the number of times each character appears in the string. I'm having trouble figuring out how to efficiently iterate over the characters in the string and keep track of the count for each character. Can anyone suggest a good way to approach this problem in Python?
Asked
Active
Viewed 52 times
-2
-
1Welcome to SO. Please don't overuse irrelevant tags. It's a Python question. You used all the other tags except the "python" tag. – S.B Dec 29 '22 at 06:28
2 Answers
0
Use the Counter class in the collections module.
from collections import Counter
string = "blueblack"
Counter(string)
Counter({'b': 2, 'l': 2, 'u': 1, 'e': 1, 'a': 1, 'c': 1, 'k': 1})
# OR
c = Counter(string)
c.items()
dict_items([('b', 2), ('l', 2), ('u', 1), ('e', 1), ('a', 1), ('c', 1), ('k', 1)])

Olabiyi Obayomi
- 126
- 4
0
As you tagged the question with the Oracle tag, I presume that Oracle solution might be OK for you as well, so - here's one option.
SQL> with
2 test (col) as
3 (select 'Littlefoot' from dual),
4 temp as
5 -- split the string into separate characters
6 (select regexp_substr(col, '[^\.]', 1, level) character
7 from test
8 connect by level <= length(col)
9 )
10 -- count them
11 select character, count(*)
12 from temp
13 group by character;
CHARACTER COUNT(*)
---------------------------------------- ----------
L 1
i 1
t 3
l 1
e 1
f 1
o 2
7 rows selected.
SQL>

Littlefoot
- 131,892
- 15
- 35
- 57
-
It was an overuse of using tags. They said: "Can anyone suggest a good way to approach this problem in **Python**?" – S.B Dec 29 '22 at 06:29