Answer:
alphabet = "abcdefghijklmnopqrstuvwxyz"
test_dups = ["zzz","dog","bookkeeper","subdermatoglyphic","subdermatoglyphics"]
test_miss = ["zzz","subdermatoglyphic","the quick brown fox jumps over the lazy dog"]
# From Section 11.2 of: # Downey, A. (2015). Think Python: How to think like a computer scientist. Needham, Massachusetts: Green Tree Press.
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
#Part 1 Construct a function, called has_duplicates, that takes a string argument and returns True if there are any repeating characters present. If not, it should return False.
def has_duplicates(stringP):
dic = histogram(stringP)
for key,value in dic.items():
if value>1:
return True
return False
# Execute has_duplicates by building a histogram using the above histogram function. Implement a loop over the items in the test_dups list.
# Display each string and indicate whether it has duplicates based on the has_duplicates function's result for that string.
# For instance, the expected output for "aaa" and "abc" would be shown below. aaa has duplicates abc has no duplicates Display a similar message for each string within test_dups.
print("***Implementation of has_duplicates function***")
for sTr in test_dups:
if has_duplicates(sTr):
print(sTr+": has duplicates")
else:
print(sTr+": has no duplicates")
#Part 2 Develop a function named missing_letters that takes a string argument and returns a new string containing all alphabet letters absent from the input string.
#The letters in the resultant string should be arranged in alphabetical order. Your implementation must utilize the histogram from the previous function and should reference the global alphabet variable directly.
#It should iterate over the alphabet letters to figure out which are missing from the input string.
#The function missing_letters should merge the list of missing letters into a string and return it.
def missing_letters(sTr):
missingLettersList = []
dic = histogram(sTr)
for l in alphabet:
if l not in dic:
missingLettersList.append(l)
missingLettersList.sort()
return "".join(missingLettersList)
#Iterate over the strings in the test_miss list and invoke missing_letters for each one. Present a line for each string outlining the missing letters.
#For example, for the string "aaa", the output should be as follows. aaa is missing letters bcdefghijklmnopqrstuvwxyz
#Should the string encompass all alphabet letters, the output should indicate that it utilizes all the letters.
#For instance, output for the alphabet string itself would be: abcdefghijklmnopqrstuvwxyz uses all the letters
#Generate a similar line for each item in test_miss.
print("\n***Implementation of missing_letters function***")
for lTm in test_miss:
sTr = missing_letters(lTm.replace(" ",""))
if sTr!="":
print(lTm+" is missing letters "+sTr)
else:
print(lTm +" uses all the letters")