1. Write a function, stringStats(inputString), that takes as input a string of l
ID: 3668381 • Letter: 1
Question
1. Write a function, stringStats(inputString), that takes as input a string of letters (possibly upper and lower case) and prints three things: the lexicographically smallest letter, the second smallest letter, and the most common letter.
You may assume that the input string contains at least two different letters. If two or more letters tie for most common, you may choose any one of them.
Ignore case when determining these values. That is, 'A' and 'a' are both considered occurrences of the letter a.
For example:
NOTE: you may not use built-in min, max, sort, or sorted functions. You may, however, use built-in string methods.
Explanation / Answer
def stringStats(s1):
s = s1.lower()
chars = dict()
for i in range(0, len(s)):
if s[i] in chars:
chars[s[i]] = chars[s[i]] + 1
else:
chars[s[i]] = 1
res1 = None
res2 = None
res3 = None
cnt = 0
for i in range(0,26):
c = chr(ord('a') + i)
if c in chars:
if chars[c] > cnt:
cnt = chars[c]
res3 = c
if res1 == None:
res1 = c
else:
if res2 == None:
res2 = c
print("In '" + s1 + "', the smallest letter is '" + res1 + "', the second smallest letter is '" + res2 + "', and the most common letter is '" + res3 + "'")
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.