Given a string, , consisting of alphabets and digits, find the frequency of each digit in the given string.
Question
Given a string, consisting of alphabets and digits, find the frequency of each digit in the given string.
Solution
Sure, here is a Python solution for your problem:
def digit_frequency(s):
# Initialize a dictionary to store the frequency of each digit
freq = {str(i): 0 for i in range(10)}
# Iterate over each character in the string
for char in s:
# If the character is a digit, increment its frequency in the dictionary
if char.isdigit():
freq[char] += 1
# Return the frequency dictionary
return freq
# Test the function
s = "a11472o5t6"
print(digit_frequency(s))
In this code, we first initialize a dictionary freq
with keys as string representations of digits from 0 to 9 and values as 0. Then we iterate over each character in the input string s
. If the character is a digit (checked using the isdigit()
method), we increment its count in the freq
dictionary. Finally, we return the freq
dictionary which contains the frequency of each digit in the string.
When you run this code with s = "a11472o5t6"
, it will print the frequency of each digit in the string.
Similar Questions
Given a string as input . Print the frequncy of each character in the string in alphabetical order of characters
Determine the frequency of the character 'a' in the string and display the result.
Python program that accepts a string and calculate the number of digits and letters and space
Write a Python program to accept a list of 10 integers and find the frequency ofany given data item (Without using predefined function
Calculate the frequency of a wave with speed of 3 x 106 m/s and wavelength of 1 x 104 m.A3 x 1010 HzB30 HzC300 HzD3000 Hz
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.