Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Python program to find top three mostly occurred letters from company name
Suppose we have a company name as string. We have to find the most common three characters from the company name and show them by following these rules −
- Pick most frequent three letters
- Sort them in descending order
- If the frequencies of some characters are same then take by their alphabetical order
So, if the input is like s = "TUTORIALSPOINT", then the output will be [[3, 'T'], [2, 'I'], [2, 'O']]
To solve this, we will follow these steps −
- x := a map containing letters and frequencies of letters in s
- res := a new list
- for each i in x, do
- insert pair (x[i], i) into ret
- res := res after sorted based on alphabetical order
- res := res after sorted based on frequency in reverse order
- return first three items from res
Example
Let us see the following implementation to get better understanding
from collections import Counter
def solve(s):
x = Counter(s)
res = []
for i in x:
res.append([x[i], i])
res = sorted(res, key=lambda cnt: cnt[1])
res = sorted(res, key=lambda cnt: cnt[0], reverse=True)
return res[:3]
s = "TUTORIALSPOINT"
print(solve(s))
Input
"TUTORIALSPOINT"
Output
[[3, 'T'], [2, 'I'], [2, 'O']]
Advertisements
