When it is required to check if the frequency of a dictionary, set and counter are same, the Counter package is imported and the input is converted into a ‘Counter’. The values of a dictionary are converted to a ‘set’ and then to a list. Based on the length of the input, the output is displayed on the console.
Below is the demonstration of the same −
from collections import Counter def check_all_same(my_input): my_dict = Counter(my_input) input_2 = list(set(my_dict.values())) if len(input_2)>2: print('The frequencies are not same') elif len (input_2)==2 and input_2-input_2>1: print('The frequencies are not same') else: print('The frequencies are same') my_str = 'xxxyyyzzzzzz' print("The string is :") print(my_str) check_all_same(my_str)
The string is : xxxyyyzzzzzz The frequencies are not same
The required packages are imported.
A method is defined that takes one input as parameter.
The input is converted to a Counter and assigned to a variable.
The values of a dictionary are accessed using the ‘.values’ method, and is converted to a list.
It is again converted to a list, and is assigned to a variable.
If the length of the input is greater than 2, it means the frequencies don’t match.
Otherwise, if the length of the input is 2 and the difference between second and first index is greater than 1, it means the frequency is not same.
Else it means the frequency is same.
Outside the method, a string is defined, and the method is called by passing this string.
The output is displayed on the console.