题目:Create a dictionary named letter_counts that contains each letter and the number of times it occurs in string1. Challenge: Letters should not be counted separately as upper-case and lower-case. Intead, all of them should be counted as lower-case.
string1 = "There is a tide in the affairs of men, Which taken at the flood, leads on to fortune. Omitted, all the voyage of their life is bound in shallows and in miseries. On such a full sea are we now afloat. And we must take the current when it serves, or lose our ventures."
string1 = string1.lower()
letter_counts = dict()
for letter in string1:
if letter not in letter_counts: # 可以用get方法代替IF
letter_counts[letter] = 0
letter_counts[letter] = letter_counts[letter] + 1
print(letter_counts)
题目:Create the dictionary characters that shows each character from the string sally and its frequency. Then, find the most frequent letter based on the dictionary. Assign this letter to the variable best_char.
sally = "sally sells sea shells by the sea shore"
characters = dict()
for char in sally:
if char not in characters:
characters[char] = 0
characters[char] = characters[char] + 1
chars = list(characters.keys())
best_char = chars[0]
for lchar in chars:
if characters[lchar] > characters[best_char]:
best_char = lchar
print(best_char)
题目:Create a dictionary called low_d that keeps track of all the characters in the string p and notes how many times each character was seen. Make sure that there are no repeats of characters as keys, such that “T” and “t” are both seen as a “t” for example.
p = "Summer is a great time to go outside. You have to be careful of the sun though because of the heat."
p = p.lower()
low_d = dict()
for char in p:
low_d[char] = low_d.get(char,0) + 1
print(low_d)