The Wayback Machine - https://web.archive.org/web/20240930204511/https://www.geeksforgeeks.org/python-dictionary-set-counter-check-frequencies-can-become/
Open In App

Python dictionary, set and counter to check if frequencies can become same

Last Updated : 24 Apr, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string.

Examples:

Input  : str = “xyyz”
Output : Yes
We can remove character ’y’ from above 
string to make the frequency of each 
character same. 

Input : str = “xyyzz” 
Output : Yes
We can remove character ‘x’ from above 
string to make the frequency of each 
character same.

Input : str = “xxxxyyzz” 
Output : No
It is not possible to make frequency of 
each character same just by removing at 
most one character from above string.

This problem has existing solution please refer Check if frequency of all characters can become same by one removal link. We will solve this problem quickly in Python. Approach is very simple,

  1. We need to count frequency of each letter in string, for this we will use Counter(input) method, it returns a dictionary having characters as keys and their respective frequencies as values.
  2. Now extract list of frequencies of each character and push these values in Set() data structure in python.
  3. Since set contains unique values, so if size of set is 1 that means frequencies of all characters were same, if size of set is 2 then check if value of first element is 1 or not ( if 1 then we can make same frequency by removing one character at most otherwise not possible ).



  4. # Function to Check if frequency of all characters
    # can become same by one removal
    from collections import Counter
      
    def allSame(input):
          
        # calculate frequency of each character
        # and convert string into dictionary
        dict=Counter(input)
      
        # now get list of all values and push it
        # in set
        same = list(set(dict.values()))
      
        if len(same)>2:
            print('No')
        elif len (same)==2 and same[1]-same[0]>1:
            print('No')
        else:
            print('Yes')
      
          
        # now check if frequency of all characters 
        # can become same
          
    # Driver program
    if __name__ == "__main__":
        input = 'xxxyyzzt'
        allSame(input)

    
    

    Output:

    No
    


Similar Reads

Python - Counter.items(), Counter.keys() and Counter.values()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It imp
3 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Meta Strings (Check if two strings can become same after a swap in one string)
Given two strings, the task is to check whether these strings are meta strings or not. Meta strings are the strings which can be made equal by exactly one swap in any of the strings. Equal string are not considered here as Meta strings. Examples: Input : str1 = "geeks" str2 = "keegs"Output : YesBy just swapping 'k' and 'g' in any of string, both wi
8 min read
Check if frequency of all characters can become same by one removal
Given a string that contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes the same in the string. Examples: Input: str = “xyyz” Output: Yes We can remove character ’y’ from above string to make the frequency of each character same. Input: str =
15+ min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
3 min read
Counting the frequencies in a list using dictionary in Python
Given an unsorted list of some elements(which may or may not be integers), Find the frequency of each distinct element in the list using a Python dictionary. Example: Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] Output: 1 : 5 2 : 4 3 : 3 4 : 3 5 : 2 Explanation: Here 1 occurs 5 times, 2 occurs 4 times and so on... The problem can be s
4 min read
Python - Frequencies of Values in a Dictionary
Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_dict = {'i
4 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Check if a grid can become row-wise and column-wise sorted after adjacent swaps
Given a grid of size n x len filled with lowercase characters. We can swap two adjacent characters in the same row and column. Now we have to check whether it is possible to arrange in such a order that every row and every column in the grid is lexicographically sorted. Examples: Input : abcde fghij olmkn trpqs xywuv Output : Yes Explanation : The
5 min read
Check if a string can become empty by recursively deleting a given sub-string
Given a string "str" and another string "sub_str". We are allowed to delete "sub_str" from "str" any number of times. It is also given that the "sub_str" appears only once at a time. The task is to find if "str" can become empty by removing "sub_str" again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
8 min read
Count number of ways array can be partitioned such that same numbers are present in same subarray
Given an array A[] of size N. The Task for this problem is to count several ways to partition the given array A[] into continuous subarrays such that the same integers are not present in different subarrays. Print the answer modulo 109 + 7. Examples: Input: A[] = {1, 2, 1, 3} Output: 2Explanation: There are two ways to break above array such that i
11 min read
Rearrange a string so that all same characters become d distance away
Given a string and a positive integer d. Some characters may be repeated in the given string. Rearrange characters of the given string such that the same characters become d distance away from each other. Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible,
14 min read
Minimize cost of increments or decrements such that same indexed elements become multiple of each other
Given two arrays A[] and B[] consisting of N integers, the task is to minimize the total cost of incrementing or decrementing array elements by 1 such that for every ith element, either A[i] is a multiple of B[i] or vice-versa. Examples: Input: A[] = {3, 6, 3}, B[] = {4, 8, 13}Output: 4Explanation:Incrementing A[0] by 1 (3 + 1 = 4) makes it multipl
6 min read
Rearrange a string so that all same characters become atleast d distance away
Given a string and a positive integer d, rearrange characters of the given string such that the same characters become at-least d distance away from each other. Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible, that should also be reported. Expected time
11 min read
Check whether the frequencies of all the characters in a string are prime or not
Given a string [Tex]str [/Tex], the task is to check if the frequencies of all the characters of the string are prime or not. If all the frequencies are prime then print [Tex]Yes [/Tex]otherwise print [Tex]No [/Tex]. Examples: Input: str = "geeksforgeeks" Output: No CharacterFrequencyg2e4k2s2f1o1r1 It is clear that only the frequencies of g, k and
6 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python | Minimum number of subsets with distinct elements using Counter
You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible. Examples: Input : arr[] = {1, 2, 3, 4} Output :1 Explanation : A single subset can contains all values and all values are distinct Input : arr[] = {1, 2, 3, 3} Output : 2 Explanatio
4 min read
Python Counter to find the size of largest subset of anagram words
Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input: ant magenta magnate tan
5 min read
Python Counter| Find duplicate rows in a binary matrix
Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicate of rows which are already present in the matrix. Examples: Input : [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] Output : (1, 1, 0, 1, 0, 1) (0, 0, 1, 0, 0, 1) We have existi
2 min read
Python Counter | Majority Element
Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows: Examples: Input : 3 3 4 2 4 4 2 4 4 Output : 4 Input : 3 3 4 2 4 4 2 4 Out
2 min read
Anagram checking in Python using collections.Counter()
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input : str1 = “abcd”, str2 = “dabc” Output : True Input : str1 = “abcf”, str
2 min read
Python Counter.update() Method
Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In this article, we will understand about the Counte
2 min read
Python | Counter Objects | elements()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-class that is used to count hashable objects. It im
6 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 = "Andrew" Output: No Approach: We have two strings
9 min read
How can one become good at Data structures and Algorithms easily?
Let us first clarify the question. There is not any easy way to become good at anything but there is an efficient way to do everything. Let us try to understand the difference between easy and efficient here with the help of a programming question! Consider the problem of "Searching an element in a sorted array". Person A solves the above problem b
4 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Create a Counter App Using React, Tailwind and Django Framework
This article will guide you in creating a Counter using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Counter in Python using the Django Framework. What is Counter App?The Counter app is a straightforward tool designed for easy
6 min read
Largest number not greater than N which can become prime after rearranging its digits
Given a number N, the task is to find the largest number less than or equal to the given number N such that on rearranging its digits it can become prime.Examples: Input : N = 99 Output : 98 Explanation : We can rearrange the digits of 98 to 89 and 89 is a prime number. Input : N = 84896 Output : 84896 Explanation : We can rearrange the digits of 8
11 min read
How to Add Same Key Value in Dictionary Python
Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python. Adding the Same Key Value in PythonDictionaries in Pytho
2 min read