Python program to find top three mostly occurred letters from company name

PythonServer Side ProgrammingProgramming

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


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]





[[3, 'T'], [2, 'I'], [2, 'O']]
Updated on 12-Oct-2021 08:09:00