Computer Science, asked by yadramsurana2753, 3 months ago

Write a program in Python to import a string and then create a dictionary which will have number of occurrences of each characters of the string. 3​

Answers

Answered by rudranshisingh00974
1

Given a string, the task is to find the frequencies of all the characters in that string and return a dictionary with key as the character and its value as its frequency in the given string.

Method #1 : Naive method

Simply iterate through the string and form a key in dictionary of newly occurred element or if element is already occurred, increase its value by 1.

# Python3 code to demonstrate 

# each occurrence frequency using 

# naive method 

  

# initializing string 

test_str = "GeeksforGeeks"

  

# using naive method to get count 

# of each element in string 

all_freq = {}

  

for i in test_str:

    if i in all_freq:

        all_freq[i] += 1

    else:

        all_freq[i] = 1

  

# printing result 

print ("Count of all characters in GeeksforGeeks is :\n "

                                        +  str(all_freq))

Output :

Count of all characters in GeeksforGeeks is : {'r': 1, 'e': 4, 'k': 2, 'G': 2, 's': 2, 'f': 1, 'o': 1}

 

Method #2 : Using collections.Counter()

The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required.

# Python3 code to demonstrate 

# each occurrence frequency using 

# collections.Counter()

from collections import Counter

  

# initializing string 

test_str = "GeeksforGeeks"

  

# using collections.Counter() to get 

# count of each element in string 

res = Counter(test_str)

  

# printing result 

print ("Count of all characters in GeeksforGeeks is :\n "

                                           +  str(res))

Output :

Count of all characters in GeeksforGeeks is : Counter({'e': 4, 's': 2, 'k': 2, 'G': 2, 'o': 1, 'r': 1, 'f': 1})

 

Similar questions