Change language

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

| |

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 an existing solution, please refer.  removal . We’ll quickly fix this problem in Python. The approach is very simple,

  1. We need to count the frequency of each letter in a line, for this we will use the method Counter (input) , it returns a dictionary in which the characters are keys, and the corresponding frequencies — values.
  2. Now extract the list of frequencies of each character and insert those values ​​into the

    # Function to check if the frequency of all characters
    # could be the same one deletion

    from collections import Counter

      

    def allSame ( input ):

     

    # calculate the frequency of each character

    # and convert the string to a dictionary

    dict = Counter ( input )

     

    # now get a list of all values ​​and click it

    # in set

    same = set < / code> ( dict . values ​​())

     

    # now check the frequency of all characters

    # may become the same

    if ( len (same) = = 1 ):

    print ’Yes’

      elif ( len (same) =  = 2 ):

    if ( list ( same) [ 0 ] = = 1 ):

    print ’ Yes’

    else :

    print ’No’

      
    # Driver program

    if __ name__ = = "__ main__" :

    input = ’xxxxyyzz’

      allSame ( input )

    Output:

     No