-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcats.py
375 lines (306 loc) · 11.1 KB
/
cats.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""Typing test implementation"""
from utils import *
from ucb import main, interact, trace
from datetime import datetime
###########
# Phase 1 #
###########
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
cnt = 0
for s in paragraphs:
if select(s) == True:
if cnt == k:
return s
cnt += 1
return ''
# END PROBLEM 1
def about(topic):
"""Return a select function that returns whether a paragraph contains one
of the words in TOPIC.
>>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy'])
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_dogs, 0)
'Cute Dog!'
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup.'], about_dogs, 1)
'Nice pup.'
"""
assert all([lower(x) == x for x in topic]), 'topics should be lowercase.'
# BEGIN PROBLEM 2
"*** YOUR CODE HERE ***"
def fun(paragraphs):
paragraphs = split(paragraphs)
for s in paragraphs:
s = remove_punctuation(s)
s = lower(s)
#print(s)
if s in topic:
return True
return False
return fun
# END PROBLEM 2
def accuracy(typed, reference):
"""Return the accuracy (percentage of words typed correctly) of TYPED
when compared to the prefix of REFERENCE that was typed.
>>> accuracy('Cute Dog!', 'Cute Dog.')
50.0
>>> accuracy('A Cute Dog!', 'Cute Dog.')
0.0
>>> accuracy('cute Dog.', 'Cute Dog.')
50.0
>>> accuracy('Cute Dog. I say!', 'Cute Dog.')
50.0
>>> accuracy('Cute', 'Cute Dog.')
100.0
>>> accuracy('', 'Cute Dog.')
0.0
"""
typed_words = split(typed)
reference_words = split(reference)
# BEGIN PROBLEM 3
"*** YOUR CODE HERE ***"
cnt = 0
for i in range(0,len(typed_words)):
if i >= len(reference_words):
break
if typed_words[i] == reference_words[i]:
cnt += 1
if len(typed_words) == 0: return 0.0
return (cnt/len(typed_words))*100
# END PROBLEM 3
def wpm(typed, elapsed):
"""Return the words-per-minute (WPM) of the TYPED string."""
assert elapsed > 0, 'Elapsed time must be positive'
# BEGIN PROBLEM 4
"*** YOUR CODE HERE ***"
return (len(typed)/5)*(60/elapsed)
# END PROBLEM 4
def autocorrect(user_word, valid_words, diff_function, limit):
"""Returns the element of VALID_WORDS that has the smallest difference
from USER_WORD. Instead returns USER_WORD if that difference is greater
than LIMIT.
"""
# BEGIN PROBLEM 5
"*** YOUR CODE HERE ***"
minn = 10000
ans = user_word
if user_word in valid_words:
return user_word
for s in valid_words:
if diff_function(user_word,s,limit) < minn and diff_function(user_word,s,limit) <= limit:
ans = s
minn = diff_function(user_word,s,limit)
return ans
# END PROBLEM 5
def shifty_shifts(start, goal, limit, now=0):
"""A diff function for autocorrect that determines how many letters
in START need to be substituted to create GOAL, then adds the difference in
their lengths.
"""
# BEGIN PROBLEM 6
flag = 0
if now > limit:
return 10000000
if start == "":
return now + len(goal)
if goal == "":
return now + len(start)
if start[0] != goal[0]:
flag = 1
else:
flag = 0
ans = shifty_shifts(start[1:],goal[1:],limit,now+flag)
return ans
# END PROBLEM 6
def meowstake_matches(start, goal, limit):
"""A diff function that computes the edit distance from START to GOAL."""
if limit < 0: # Fill in the condition
# BEGIN
"*** YOUR CODE HERE ***"
return 0
# END
elif len(start) == 0 or len(goal) == 0:
return len(start) + len(goal)
elif start[0] == goal[0]: # Feel free to remove or add additional cases
# BEGIN
"*** YOUR CODE HERE ***"
return meowstake_matches(start[1:],goal[1:],limit)
# END
else:
add_diff = meowstake_matches(start,goal[1:],limit-1) # Fill in these lines
remove_diff = meowstake_matches(start[1:],goal,limit-1)
substitute_diff = meowstake_matches(start[1:],goal[1:],limit-1)
# BEGIN
"*** YOUR CODE HERE ***"
return min(add_diff,remove_diff,substitute_diff) + 1
# END
def final_diff(start, goal, limit):
"""A diff function. If you implement this function, it will be used."""
assert False, 'Remove this line to use your final_diff function'
###########
# Phase 3 #
###########
def report_progress(typed, prompt, id, send):
"""Send a report of your id and progress so far to the multiplayer server."""
# BEGIN PROBLEM 8
"*** YOUR CODE HERE ***"
cnt = 0
for i in range(0,len(typed)):
if typed[i] == prompt[i]:
cnt+=1
else:
break
print("ID:",id,"Progress:",cnt/len(prompt))
return cnt / len(prompt)
# END PROBLEM 8
def fastest_words_report(times_per_player, words):
"""Return a text description of the fastest words typed by each player."""
game = time_per_word(times_per_player, words)
fastest = fastest_words(game)
report = ''
for i in range(len(fastest)):
words = ','.join(fastest[i])
report += 'Player {} typed these fastest: {}\n'.format(i + 1, words)
return report
def time_per_word(times_per_player, words):
"""Given timing data, return a game data abstraction, which contains a list
of words and the amount of time each player took to type each word.
Arguments:
times_per_player: A list of lists of timestamps including the time
the player started typing, followed by the time
the player finished typing each word.
words: a list of words, in the order they are typed.
"""
# BEGIN PROBLEM 9
"*** YOUR CODE HERE ***"
ans = []
for i in range(0,len(times_per_player)):
ans.append([])
for j in range(1,len(words)+1):
ans[i].append(times_per_player[i][j]-times_per_player[i][j-1])
return game(words,ans)
# END PROBLEM 9
def fastest_words(game):
"""Return a list of lists of which words each player typed fastest.
Arguments:
game: a game data abstraction as returned by time_per_word.
Returns:
a list of lists containing which words each player typed fastest
"""
players = range(len(all_times(game))) # An index for each player
words = range(len(all_words(game))) # An index for each word
# BEGIN PROBLEM 10
"*** YOUR CODE HERE ***"
ans = []
for i in players:
ans.append([])
for j in words:
minn = 1000000
minnk = 1
for k in players:
if all_times(game)[k][j] < minn:
minn = all_times(game)[k][j]
minnk = k
if minn == all_times(game)[i][j] and minnk == i:
ans[i].append(all_words(game)[j])
return ans
# END PROBLEM 10
def game(words, times):
"""A data abstraction containing all words typed and their times."""
assert all([type(w) == str for w in words]), 'words should be a list of strings'
assert all([type(t) == list for t in times]), 'times should be a list of lists'
assert all([isinstance(i, (int, float)) for t in times for i in t]), 'times lists should contain numbers'
assert all([len(t) == len(words) for t in times]), 'There should be one word per time.'
return [words, times]
def word_at(game, word_index):
"""A selector function that gets the word with index word_index"""
assert 0 <= word_index < len(game[0]), "word_index out of range of words"
return game[0][word_index]
def all_words(game):
"""A selector function for all the words in the game"""
return game[0]
def all_times(game):
"""A selector function for all typing times for all players"""
return game[1]
def time(game, player_num, word_index):
"""A selector function for the time it took player_num to type the word at word_index"""
assert word_index < len(game[0]), "word_index out of range of words"
assert player_num < len(game[1]), "player_num out of range of players"
return game[1][player_num][word_index]
def game_string(game):
"""A helper function that takes in a game object and returns a string representation of it"""
return "game(%s, %s)" % (game[0], game[1])
enable_multiplayer = False # Change to True when you
##########################
# Extra Credit #
##########################
key_distance = get_key_distances()
def key_distance_diff(start, goal, limit):
""" A diff function that takes into account the distances between keys when
computing the difference score."""
start = start.lower() #converts the string to lowercase
goal = goal.lower() #converts the string to lowercase
# BEGIN PROBLEM EC1
"*** YOUR CODE HERE ***"
# END PROBLEM EC1
def memo(f):
"""A memoization function as seen in John Denero's lecture on Growth"""
cache = {}
def memoized(*args):
if args not in cache:
cache[args] = f(*args)
return cache[args]
return memoized
key_distance_diff = count(key_distance_diff)
def faster_autocorrect(user_word, valid_words, diff_function, limit):
"""A memoized version of the autocorrect function implemented above."""
# BEGIN PROBLEM EC2
"*** YOUR CODE HERE ***"
# END PROBLEM EC2
##########################
# Command Line Interface #
##########################
def run_typing_test(topics):
"""Measure typing speed and accuracy on the command line."""
paragraphs = lines_from_file('data/sample_paragraphs.txt')
select = lambda p: True
if topics:
select = about(topics)
i = 0
while True:
reference = choose(paragraphs, select, i)
if not reference:
print('No more paragraphs about', topics, 'are available.')
return
print('Type the following paragraph and then press enter/return.')
print('If you only type part of it, you will be scored only on that part.\n')
print(reference)
print()
start = datetime.now()
typed = input()
if not typed:
print('Goodbye.')
return
print()
elapsed = (datetime.now() - start).total_seconds()
print("Nice work!")
print('Words per minute:', wpm(typed, elapsed))
print('Accuracy: ', accuracy(typed, reference))
print('\nPress enter/return for the next paragraph or type q to quit.')
if input().strip() == 'q':
return
i += 1
@main
def run(*args):
"""Read in the command-line argument and calls corresponding functions."""
import argparse
parser = argparse.ArgumentParser(description="Typing Test")
parser.add_argument('topic', help="Topic word", nargs='*')
parser.add_argument('-t', help="Run typing test", action='store_true')
args = parser.parse_args()
if args.t:
run_typing_test(args.topic)