-
Notifications
You must be signed in to change notification settings - Fork 0
/
DictionariesStrings Python
42 lines (26 loc) · 1.61 KB
/
DictionariesStrings Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# counting how many times each word is in a text
# Provided is a string saved to the variable name sentence.
# Split the string into a list of words, then create a dictionary that contains each word and the number of times it occurs.
# Save this dictionary to the variable name word_counts.
sentence = "The dog chased the rabbit into the forest but the rabbit was too quick."
words = sentence.split()
word_counts = {}
for word in words:Provided is a string saved to the variable name sentence. Split the string into a list of words, then create a dictionary that contains each word and the number of times it occurs. Save this dictionary to the variable name word_counts.
if word not in word_counts:
word_counts[word]=0Provided is a string saved to the variable name sentence. Split the string into a list of words, then create a dictionary that contains each word and the number of times it occurs. Save this dictionary to the variable name word_counts.
word_counts[word]=word_counts[word]+1
# 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 = {}
for char in sally:
if char not in characters:
characters[char]=0
characters[char]+=1
best_char_freq = 0
for c in characters:
if characters[c] > best_char_freq:
best_char_freq=characters[c]
for key, value in characters.items():
if value == best_char_freq:
best_char = key