-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordlengths.py
More file actions
57 lines (38 loc) · 1.36 KB
/
wordlengths.py
File metadata and controls
57 lines (38 loc) · 1.36 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Get dictionary of word-length: {words}.
Given a phrase, return dictionary keyed by word-length, with the value for
each length being the set of words of that length.
For example::
>>> answer = word_lengths("cute cats chase fuzzy rats")
This should return {4: {'cute', 'cats'}, 5: {'chase', 'fuzzy', 'rats'}},
but since both dictionaries and sets are unordered, we can't just check if
it matches that exact string, so we'll test more carefully::
>>> sorted(answer.keys())
[4, 5]
>>> answer[4] == {'cute', 'cats', 'rats'}
True
>>> answer[5] == {'chase', 'fuzzy'}
True
Punctuation should be considered part of a word, so you only need to
split the string on whitespace::
>>> answer = word_lengths("Hi, I'm Balloonicorn")
>>> sorted(answer.keys())
[3, 12]
>>> answer[3] == {'Hi,', "I'm"}
True
>>> answer[12] == {"Balloonicorn"}
True
"""
def word_lengths(sentence):
"""Get dictionary of word-length: {words}."""
length_counts = {}
words = sentence.split(" ")
for word in words:
if len(word) not in length_counts:
length_counts[len(word)] = set([word])
else:
length_counts[len(word)].add(word)
return length_counts
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. NOTHING ESCAPES YOU!\n"