Open In App

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

Last Updated : 24 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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 - Matrix elements Frequencies Counter
Sometimes, while working with python Matrix, we can have a problem in which we need to find frequencies of all elements in Matrix. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using Counter() + sum() + map() The combination of above methods can be used to perfo
5 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
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
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 - Associated Values Frequencies in Dictionary
Sometimes, while working with dictionaries, we can have problem in which we need to compute the values associated to each value in dictionary in records list. This kind of problem is peculiar, but can have application in development domains. Lets discuss certain way in which this task can be performed. Counting Associated Values Frequencies in Dict
5 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
three90RightbarBannerImg