Reputation: 485
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
Upvotes: 1
Views: 117
Reputation: 4779
You can use Counter
and achieve this.
Counter
. This will give you a dict
dict
first by the values in descending order and then by the keys value in ascending orderfrom 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)
Upvotes: 1
Reputation: 1089
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())
Upvotes: 1