Advertisement
Guest User

pythontutor

a guest
Jul 21st, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. import string
  2. # takes a non-empty string and returns a lowercase string that contains the most frequently
  3. # occurring letter(s) in s in alphabetical order (ignoring case in the original string)
  4. # you will likely need a nested loop for this...
  5. def mostFrequentLetter(s):
  6.     d = {}
  7.     for c in s.lower():
  8.         #Ignore other non-alphabetic characters.
  9.         if c in string.ascii_lowercase:
  10.             d[c] = d.get(c, 0) + 1
  11.     #Make a list of tuples.
  12.     t = [(v, k) for k, v in d.items()]
  13.     #Sort the list by the elements in tuples.
  14.     t.sort(key = lambda x: (-x[0], x[1]))
  15.     if not t:
  16.         return ''
  17.     max_count = t[0][0]
  18.     return ''.join(c[1] for c in t if c[0] == max_count)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement