Python program to find Most Frequent Character in a String

PythonServer Side ProgrammingProgramming

When it is required to find the most frequent character in a string, an empty dictionary is created, and the elements in the string are iterated over. When a character is found in the dictionary, it is increment, else it is assigned to 1. The maximum of the values in the dictionary is found, and assigned to a variable.

Example

Below is a demonstration of the same

my_string = "Python-Interpreter"

print ("The string is : ")
print(my_string)

max_frequency = {}
for i in my_string:
   if i in max_frequency:
      max_frequency[i] += 1
   else:
      max_frequency[i] = 1
my_result = max(max_frequency, key = max_frequency.get)

print ("The maximum of all characters is : ")
print(my_result)

Output

The string is :
Python-Interpreter
The maximum of all characters in Python-Interpreter is :
e

Explanation

  • A string is defined, and is displayed on the console.

  • An empty dictionary is created.

  • The letters in the string are iterated over, and if it has been matched to a character, it is incremented.

  • Else, it is assigned to 1.

  • The maximum of the values in the dictionary is determined.

  • It is assigned to a variable.

  • This variable is displayed as output on the console.

raja
Published on 09-Sep-2021 06:14:20
Advertisements