Programs · Program 10-7
Q.Program 10-7: Write a program to count the number of times a character appears in a given string.
Odisha ChseTextbookSubjective· 3mImportance★★★★★est
37% · 11/30 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →One pass over the string with an if/else on ch in dic counts every character: existing key -> +1, new character -> new key with count 1.
The idea. Counting occurrences is the classic dictionary pattern: the character is the key, its running count the value. The membership test ch in dic splits the two cases — first sighting (create the key) versus repeat (increment). One linear pass, O(n), no nested searching.
Program 10-7:
st = input("Enter a string: ")
dic = {}
for ch in st:
if ch in dic: # seen before -> increment its count
dic[ch] = dic[ch] + 1
else: # first time -> create the key with count 1
dic[ch] = 1
print("Number of times each character appears in the string:")
for key in dic:
print(key, ":", dic[key])
Sample run:
Enter a string: HelloWorld
Number of times each character appears in the string:
H : 1
e : 1
l : 3
o : 2
W : 1
r : 1
d : 1
Trace for 'Hello' (first five characters):
| ch | in dic? | action | dic after |
|---|---|---|---|
| H | no | create, 1 | {'H': 1} |
| e | no | create, 1 | {'H': 1, 'e': 1} |
| l | no | create, 1 | {'H': 1, 'e': 1, 'l': 1} |
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.