Python: Count most and least common characters in a given string
21. Count the Most and Least Common Characters in a String
Write a Python program to count the most and least common characters in a given string.
Sample Solution:
Python Code:
# Import the Counter class from the collections module
from collections import Counter
# Define a function 'max_least_char' that finds the most and least common characters in a string
def max_least_char(str1):
# Create a Counter object 'temp' to count the occurrences of characters in 'str1'
temp = Counter(str1)
# Find the character with the maximum count using 'max' and the character with the minimum count using 'min'
max_char = max(temp, key=temp.get)
min_char = min(temp, key=temp.get)
# Return a tuple containing the most and least common characters
return (max_char, min_char)
# Create a string 'str1'
str1 = "hello world"
# Print a message to indicate the display of the original string
print("Original string: ")
print(str1)
# Call the 'max_least_char' function with 'str1' and store the result in 'result'
result = max_least_char(str1)
# Print a message to indicate the display of the most common character in the string
print("\nMost common character of the said string:", result[0])
# Print a message to indicate the display of the least common character in the string
print("Least common character of the said string:", result[1])
Sample Output:
Original string: hello world Most common character of the said string: l Least common character of the said string: h
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to count character frequencies in a string and print both the most common and least common characters using collections.Counter.
- Write a Python program to use a dictionary to tally character counts and then determine which character appears most and which least.
- Write a Python program to iterate over a string and compare character frequencies to identify the maximum and minimum occurring characters.
- Write a Python program to implement a function that returns the most and least common characters from a given string.
Python Code Editor:
Previous: Write a Python program to find the item with maximum frequency in a given list.
Next: Write a Python program to insert an element at the beginning of a given OrderedDictionary.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.