Solution for Smallest alphabet with maximum occurences in python string
is Given Below:
There is a python string for example “programming”
I have to find the smallest letter with highest occurrences.
That is for given input string = “programming”
the output should be g 2
I tried this , but not able to achieve the solution
str1 = 'programming'
max_freq = {}
for i in str1:
if i in max_freq:
max_freq[i] += 1
else:
max_freq[i] = 1
res = max(max_freq, key = max_freq.get)
Any help would be really appreciated
You can use Counter
and achieve this.
- Count the frequency of each letter using
Counter
. This will give you adict
- Sort the
dict
first by the values in descending order and then by the keys value in ascending order - The First item is your answer
from collections import Counter
str1 = 'programming'
d = Counter(str1)
d = sorted(d.items(), key= lambda x: (-x[1], x[0]))
print(d[0])
('g', 2)
For your code to work, replace the last line with this
res = sorted(max_freq.items(), key=lambda x: (-x[1], x[0]))[0]
res
will have the smallest letter with maximum occurrences. i.e, ('g', 2)
You are close, you just aren’t getting the max correctly. If all you care about is the number, then you could modify your example slightly:
str1 = 'programming'
max_freq = {}
for i in str1:
if i in max_freq:
max_freq[i] += 1
else:
max_freq[i] = 1
res = max(max_freq.values())