Find the least frequent character in a string in Python

This Python tutorial will teach you how to find the least frequent character in a string. In a Python program, sometimes we may need to do some operation on the least occurring character in a given string. Which is why we need to know different ways to do so. Let’s understand it further in this tutorial.

We will discuss the following ways to get the least occurring character in a string. Be thorough with the codes to grasp the concept.

Method 1

This is a simple and naive method. Here is the algorithm.

  • Create an empty dictionary.
  • Use a for loop to iterate through all the characters in the string.
  • If the character already exists in the dictionary, increment its value by 1. Otherwise, initialize its value with 1. Note that the keys for the dictionary are the characters of the given string.
  •  The obtained dictionary contains values of different characters in the key-value pairs. Find the key with minimum value.
  • Typecast it to string and print it.

Have a look at the code to get the logic of the program.

string = "aabbcddeeff"

dict ={}

for character in string:
    if character in dict:
        dict[character]+=1
    else:
        dict[character]=1
        
print("The least frequent character is", str(min(dict, key = dict.get)))

Output:

The least frequent character is c

Method 2

Another method to solve this problem makes the use of the collection library. Collection library has a Counter() which can be used to store the frequency of all the characters of the string. Now if we want to find the minimum occurring character in the string, we will need to use the min() function as we did in the previous method. See the code for a better understanding.

import collections

string = "aabbcddeeff"
count =collections.Counter(string)

print("The least frequent character is", str(min(count, key = count.get)))

Output:

The least frequent character is c

Thank you.

Also read: Find the most frequent value in a list in Python

Leave a Reply

Your email address will not be published. Required fields are marked *