Character FrequencyGiven a string as input . Print the frequncy of each character in the string in alphabetical order of charactersConstraints:Input format :s1 -> string as input Output format :List of all characters along with its frequency in string Example:Input 1:googleOutput 1:['e', 1] ['g', 2] ['l', 1] ['o', 2]Input 2:PythonOutput 2:['P', 1] ['h', 1] ['n', 1] ['o', 1] ['t', 1] ['y', 1]
Question
Character FrequencyGiven a string as input . Print the frequncy of each character in the string in alphabetical order of charactersConstraints:Input format :s1 -> string as input Output format :List of all characters along with its frequency in string Example:Input 1:googleOutput 1:['e', 1] ['g', 2] ['l', 1] ['o', 2]Input 2:PythonOutput 2:['P', 1] ['h', 1] ['n', 1] ['o', 1] ['t', 1] ['y', 1]
Solution
Here is a step-by-step solution in Python:
- First, we need to define a function that takes a string as input.
def char_frequency(str1):
- Then, we need to create a dictionary to store the frequency of each character.
dict = {}
- Next, we iterate over each character in the string. If the character is already in the dictionary, we increment its count. If it's not, we add it to the dictionary with a count of 1.
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
- Finally, we return the dictionary sorted by keys (characters) in alphabetical order.
return sorted(dict.items())
- Now, we can call the function with a string to get the frequency of each character.
print(char_frequency('google'))
print(char_frequency('Python'))
This will output:
[('e', 1), ('g', 2), ('l', 1), ('o', 2)]
[('P', 1), ('h', 1), ('n', 1), ('o', 1), ('t', 1), ('y', 1)]
This means that in the string 'google', 'e' appears 1 time, 'g' appears 2 times, 'l' appears 1 time, and 'o' appears 2 times. Similarly, you can interpret the output for 'Python'.
Similar Questions
Given a string as input . Print the frequncy of each character in the string in alphabetical order of characters
Define a function print_all_chars(string1). The function prints all the characters in a given string using while loop and return the number of charachters in the string.Exampleprint_all_chars('python') -> 6> p> y> t> h> o> nHintlen() returns the length of a string.the element on index i can be accessed by using string[i].
Write a python program to count the number of characters of alphabets 'O' and 'i' from the given file
Determine the frequency of the character 'a' in the string and display the result.
Write a Python program to count the number of occurrences of a specific character in a string
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.