- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python dictionary, set and counter to check if frequencies can become same
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.
- Check if frequency of all characters can become same by one removal in Python
- Python counter and dictionary intersection example
- String slicing in Python to check if a can become empty by recursive deletion
- Python - Check if dictionary is empty
- Meta Strings (Check if two strings can become same after a swap in one string) in C++
- Check if a string can become empty by recursively deleting a given sub-string in Python
- Python - Check if frequencies of all characters of a string are different
- Python program to check if both halves of the string have same set of characters.
- Counting the frequencies in a list using dictionary in Python
- Check if both halves of the string have same set of characters in Python
- Check if a number has same number of set and unset bits in C++
- How to check if a key exists in a Python dictionary?
- Check if lowercase and uppercase characters are in same order in Python
- Counter Size and Counter Overflow
- Check if both halves of the string have the same set of characters in Python