Python: Count most and least common characters in a given 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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics