# Python - Check if frequencies of all characters of a string are different

PythonServer Side ProgrammingProgramming

In this article we will see how to find the frequency of each character in a given string. Then see if two or more characters have the same frequency in the given string or not. We will accomplish this in two steps. In the first program we will just find out the frequency of each character.

## Frequency of each character

Here we find the frequency of each character in the given input screen. We declare a empty dictionary and then add each character as a string. We also assign keys to each of the character to create the key-value pair needed by the dictionary.

### Example

Live Demo

in_string = "She sells sea shells"
dic1 = {}
for k in in_string:
if k in dic1.keys():
dic1[k]+=1
else:
dic1[k]=1
print(dic1)
for k in dic1.keys():
print(k, " repeats ",dic1[k]," time's")

### Output

Running the above code gives us the following result −

{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}
S repeats 1 time's
h repeats 2 time's
e repeats 4 time's
repeats 3 time's
s repeats 5 time's
l repeats 4 time's
a repeats 1 time's

## Unique Frequency of each character

Next we extend the above program to find out the frequency for each unique character. If the unique value of the frequency is greater than one, then we conclude that not all characters have same frequency.

### Example

Live Demo

in_string = "She sells sea shells"
dic1 = {}
for k in in_string:
if k in dic1.keys():
dic1[k]+=1
else:
dic1[k]=1
print(dic1)
u_value = set( val for udic in dic1 for val in (dic1.values()))
print("Number of Unique frequencies: ",len(u_value))
if len(u_value) == 1:
print("All character have same frequiency")
else:
print("The characters have different frequencies.")

### Output

Running the above code gives us the following result −

{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}
Number of Unique frequencies: 5
The characters have different frequencies.