Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

NOTE: You may not use any functions from external modules loaded by \'import.\'

ID: 3790875 • Letter: N

Question

NOTE: You may not use any functions from external modules loaded by 'import.' In addition, you may not use dictionaries, list comprehensions, or other Python language features not yet taught in this class. The point of these exercises is to practice very basic components of programming.

1. Write a function, printStringStats(inputString), that takes as input a string of lowercase letters and prints three things: the lexicographically largest letter (z > y > ... > a), the third largest letter, and the most common letter along with how many times it occurs.

You may assume the string is at least one character long. But you may not assume that it contains at least three different characters. If fewer than three different letters appear in the string, print something appropriate for the third largest (e.g. "There is no third largest letter.")

If two or more letters tie for most common, you may choose any one of them.

For example:

NOTE: you may not use built-in min, max, sort, or sorted functions. You may not use any built-in string methods. Use one or more simple loops, and simple comparison (<,>, ==, !=) operators only.

Explanation / Answer

def printStringStats(st):
   dic = {}
   largest = st[0]
   second = 'a'
   third = 'a'
   for i in range(0, len(st)):
       if st[i] in dic:
           dic[st[i]] = dic[st[i]] + 1
       else:
           dic[st[i]] = 1

   mostCommon = st[0]
   keys = dic.keys()
   for i in range(0, len(keys)):
       if dic[mostCommon] < dic[keys[i]]:
           mostCommon = keys[i]

   for i in range(0, len(keys)):
       if keys[i] > largest:
           third = second
           second = largest
           largest = keys[i]
       elif keys[i] > second:
           third = second
           second = keys[i]
       elif keys[i] > third:
           third = keys[i]

   print 'In ' + st + ', the largest letter is '' + largest,
   if len(keys) >= 3:
       print ', the third largest letter is '' + third + '','
   else:
       print ', there is no third largest letter,'
   print 'and the most common letter is ' + mostCommon + ' occuring '' + str(dic[mostCommon]) + '' times'


printStringStats('aaczzcqzqqqzqc')