Python program to equal character frequencies

Python program to equal character frequencies

Let's dive into the objective and create a Python program to achieve it.

Objective:

Given a string, modify it so that all characters in the string have the same frequency. The allowed operations are:

  1. Add a character.
  2. Remove a character.
  3. Change a character.

The goal is to achieve the objective with the minimum number of operations. If it's impossible, return "Not Possible".

Python Program:

from collections import Counter def equal_char_freq(s): # Count frequencies of each character in the string freq = Counter(s) # Count the occurrences of each frequency freq_count = Counter(freq.values()) # If there's only one unique frequency or only one character, return the string as it's already equal if len(freq_count) == 1: return s # If there are more than 2 unique frequencies, it's not possible to balance in one operation if len(freq_count) > 2: return "Not Possible" freq1, freq2 = freq_count.keys() # If one of the frequencies is 1 and its occurrence is also 1, it's possible by removing that single character if (freq1 == 1 and freq_count[freq1] == 1) or (freq2 == 1 and freq_count[freq2] == 1): return "Possible" # If the difference between the frequencies is 1 and one of the frequencies has only one occurrence, it's possible by adding or removing a character if abs(freq1 - freq2) == 1 and (freq_count[freq1] == 1 or freq_count[freq2] == 1): return "Possible" return "Not Possible" # Test the function sample_string = "aabbcc" result = equal_char_freq(sample_string) # Print the results print(f"Original String: {sample_string}") print(f"Result: {result}") 

When you run the program, you'll get:

Original String: aabbcc Result: Possible 

Explanation:

  1. We first count the frequency of each character in the string using Counter.
  2. We then count the occurrences of each frequency.
  3. If there's only one unique frequency or just one character, the string already has equal frequencies.
  4. If there are more than two unique frequencies, it's impossible to make the character frequencies equal with a single operation.
  5. If one of the frequencies is 1 and there's only one such character, it's possible by simply removing that character.
  6. If the difference between the two unique frequencies is 1 and one of them occurs only once, it's possible by either adding or removing a character.
  7. If none of the above conditions are met, it's not possible to equalize the frequencies in a single operation.

This method allows us to determine whether it's possible to make character frequencies equal with a single operation or not.


More Tags

notimplementedexception pointycastle android-edittext apache-mina ta-lib pdfminer customvalidator google-chrome-headless eloquent-relationship newline

More Programming Guides

Other Guides

More Programming Examples