Alphabet Digit Count and Most Occurring Character in String
In this class, we do programs on alphabet digit count and most occurring character in string.
For Complete YouTube Video: Click Here
Table of Contents
Alphabet Digit and Special Character Count Program
Q1) write a python program to check the count of alphabets, digits, and special characters in the given string.
Example:
x=” learning monkey01″
In the given string, we are having alphabets, digits, and special characters.
01 are digits, and space is a special character.
The remaining are alphabets.
We have to count the number of alphabets, digits, and special characters in the string.
Output:
alphabets = 14
digits=2
special symbols = 1
Logic
if((ch>=’a’and ch <=’z’) we use this if statement.
Here we are comparing ch>=” a” i.e., Unicode values are compared.
Suppose you don’t know how strings are saved using Unicode characters in python. Click here.
The Unicode value for character a is 97, and for b is 98.
Take the characters in the string one by one and write logic to check the character is an alphabet, digit, or special character.
Program
string= input("enter your string")
alphacount=0
digicount=0
specialcount=0
for ch in string:
if((ch>='a'and ch <='z') or (ch>='A'and ch <='Z')):
alphacount+=1
elif (ch>='0' and ch <='9'):
digicount+=1
else:
specialcount+=1
print("no of alphabets = ",alphacount)
print("no of digits = ",digicount)
print("no of special characters = ",specialcount)
In the above program, we use the loop to take characters in a string.
We use if conditional statements to check the character is alphabet, digit, or special.
Update the count according to condition.
Most Occurring Character
Q2) Write a program to find the most occurring character in the given string.
Example:
x=” learning monkey.”
From the above string, the most occurring character is n.
Output: n
Logic
Take each character and compare its ASCII value and update the count.
Similar to above. But we have 256 ASCII characters.
To identify all 256 characters separately, use a list of size 256.
Initially, take all zero’s in the list.
Take each character from the string and check the ASCII value.
For example, if the ASCII value is 90. Increment count at index position 90 in the list.
Finally, pick the maximum count from the list.
Program
string=input("enter your string")
asciilist=[0]*255
length=len(string)
i=0
while(i<length):
asciiint=ord(string[i])
asciilist[asciiint]+=1
i+=1
maxfreqchar=asciilist.index(max(asciilist))
print(chr(maxfreqchar))
We used ord and chr functions to convert the given character to ASCII value. And vice versa.