-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcats.py
477 lines (386 loc) · 14.7 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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
"""Typing test implementation"""
# from itertools import count
from operator import itemgetter
# from turtle import update
# from numpy import array, diff
# from soupsieve import closest
from utils import lower, split, remove_punctuation, lines_from_file
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.
Arguments:
paragraphs: a list of strings
select: a function that returns True for paragraphs that can be selected
k: an integer
>>> ps = ['hi', 'how are you', 'fine']
>>> s = lambda p: len(p) <= 4
>>> choose(ps, s, 0)
'hi'
>>> choose(ps, s, 1)
'fine'
>>> choose(ps, s, 2)
''
"""
# BEGIN PROBLEM 1
length = len(paragraphs)
i= 0
count = 0
while(i < length):
if select(paragraphs[i]):
if count == k:
return paragraphs[i]
count+=1
i+=1
return ''
# END PROBLEM 1
def about(topic):
"""Return a select function that returns whether
a paragraph contains one of the words in TOPIC.
Arguments:
topic: a list of words related to a subject
>>> 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
def check(paragraph):
remove_punc = remove_punctuation(paragraph)
words = remove_punc.split()
words = list(map(lower, words))
count = 0
for word in topic:
if lower(word) in words:
return True
return False
return check
# 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.
Arguments:
typed: a string that may contain typos
reference: a string without errors
>>> 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
>>> accuracy('', '')
100.0
"""
typed_words = split(typed)
reference_words = split(reference)
count = 0
if(typed =="" and reference == ""):
return 100.0
elif len(typed_words) == 0 or len(reference_words) == 0:
return 0.0
else:
total = len(typed_words)
for i in range(min(len(typed_words),len(reference_words))):
if typed_words[i] == reference_words[i]:
count+=1
return (count/total) * 100
# END PROBLEM 3
def wpm(typed, elapsed):
"""Return the words-per-minute (WPM) of the TYPED string.
Arguments:
typed: an entered string
elapsed: an amount of time in seconds
>>> wpm('hello friend hello buddy hello', 15)
24.0
>>> wpm('0123456789',60)
2.0
"""
assert elapsed > 0, 'Elapsed time must be positive'
# BEGIN PROBLEM 4
return ((len(typed) / 5) / (elapsed / 60))
# END PROBLEM 4
###########
# Phase 2 #
###########
def autocorrect(typed_word, valid_words, diff_function, limit):
"""Returns the element of VALID_WORDS that has the smallest difference
from TYPED_WORD. Instead returns TYPED_WORD if that difference is greater
than LIMIT.
Arguments:
typed_word: a string representing a word that may contain typos
valid_words: a list of strings representing valid words
diff_function: a function quantifying the difference between two words
limit: a number
>>> ten_diff = lambda w1, w2, limit: 10 # Always returns 10
>>> autocorrect("hwllo", ["butter", "hello", "potato"], ten_diff, 20)
'butter'
>>> first_diff = lambda w1, w2, limit: (1 if w1[0] != w2[0] else 0) # Checks for matching first char
>>> autocorrect("tosting", ["testing", "asking", "fasting"], first_diff, 10)
'testing'
"""
# BEGIN PROBLEM 5
def get_key(val,dictionary):
for key, value in dictionary.items():
if value == val:
return key
if typed_word in valid_words:
return typed_word
else:
new_dict = {}
for i in range(len(valid_words)):
new_dict.update({str(i): diff_function(typed_word, valid_words[i], limit)})
all_values = new_dict.values()
min_value = min(all_values)
if min_value > limit:
return typed_word
else:
value = valid_words[int(get_key(min_value, new_dict))]
return value
# END PROBLEM 5
def feline_flips(start, goal, limit):
"""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 and returns the result.
Arguments:
start: a starting word
goal: a string representing a desired goal word
limit: a number representing an upper bound on the number of chars that must change
>>> big_limit = 10
>>> feline_flips("nice", "rice", big_limit) # Substitute: n -> r
1
>>> feline_flips("range", "rungs", big_limit) # Substitute: a -> u, e -> s
2
>>> feline_flips("pill", "pillage", big_limit) # Don't substitute anything, length difference of 3.
3
>>> feline_flips("roses", "arose", big_limit) # Substitute: r -> a, o -> r, s -> o, e -> s, s -> e
5
>>> feline_flips("rose", "hello", big_limit) # Substitute: r->h, o->e, s->l, e->l, length difference of 1.
5
"""
# BEGIN PROBLEM 6
# assert False, 'Remove this line'
def check(count, index):
if(count + abs(len(start)-len(goal)) > limit):
return limit + 1
elif index == (min(len(start),len(goal))):
return count + abs(len(start)-len(goal))
else:
if(start[index] != goal[index]):
return check(count + 1, index + 1)
else:
return check(count, index + 1)
return check(0,0)
# END PROBLEM 6
def minimum_mewtations(start, goal, limit):
"""A diff function that computes the edit distance from START to GOAL.
This function takes in a string START, a string GOAL, and a number LIMIT.
Arguments:
start: a starting word
goal: a goal word
limit: a number representing an upper bound on the number of edits
>>> big_limit = 10
>>> minimum_mewtations("cats", "scat", big_limit) # cats -> scats -> scat
2
>>> minimum_mewtations("purng", "purring", big_limit) # purng -> purrng -> purring
2
>>> minimum_mewtations("ckiteus", "kittens", big_limit) # ckiteus -> kiteus -> kitteus -> kittens
3
"""
# assert False, 'Remove this line'
if limit < 0:
return limit + 1
elif len(start) == 0 or len(goal) == 0:
return max(len(start),len(goal))
elif start[:1] == goal [:1]:
return minimum_mewtations(start[1:], goal[1:], limit)
else:
add = 1 + minimum_mewtations(start, goal[1:], limit - 1)
remove = 1 + minimum_mewtations(start[1:], goal, limit - 1)
sub = 1 + minimum_mewtations(start[1:], goal[1:], limit - 1)
# print("DEBUG Add: ",add)
return min(add,remove,sub)
#END
def final_diff(start, goal, limit):
"""A diff function that takes in a string START, a string GOAL, and a number LIMIT.
If you implement this function, it will be used."""
assert False, 'Remove this line to use your final_diff function.'
FINAL_DIFF_LIMIT = 6 # REPLACE THIS WITH YOUR LIMIT
###########
# Phase 3 #
###########
def report_progress(sofar, prompt, user_id, upload):
"""Upload a report of your id and progress so far to the multiplayer server.
Returns the progress so far.
Arguments:
sofar: a list of the words input so far
prompt: a list of the words in the typing prompt
user_id: a number representing the id of the current user
upload: a function used to upload progress to the multiplayer server
>>> print_progress = lambda d: print('ID:', d['id'], 'Progress:', d['progress'])
>>> # The above function displays progress in the format ID: __, Progress: __
>>> print_progress({'id': 1, 'progress': 0.6})
ID: 1 Progress: 0.6
>>> sofar = ['how', 'are', 'you']
>>> prompt = ['how', 'are', 'you', 'doing', 'today']
>>> report_progress(sofar, prompt, 2, print_progress)
ID: 2 Progress: 0.6
0.6
>>> report_progress(['how', 'aree'], prompt, 3, print_progress)
ID: 3 Progress: 0.2
0.2
"""
# BEGIN PROBLEM 8
count = 0
for i in range(len(sofar)):
if sofar[i] == prompt[i]:
count+=1
else:
break
result = count / (len(prompt))
upload({'id': user_id, 'progress': result})
return result
# END PROBLEM 8
def time_per_word(words, times_per_player):
"""Given timing data, return a match data abstraction, which contains a
list of words and the amount of time each player took to type each word.
Arguments:
words: a list of words, in the order they are typed.
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.
>>> p = [[75, 81, 84, 90, 92], [19, 29, 35, 36, 38]]
>>> match = time_per_word(['4collar', 'plush', 'blush', 'repute'], p)
>>> get_words(match)
['collar', 'plush', 'blush', 'repute']
>>> get_times(match)
[[6, 3, 6, 2], [10, 6, 1, 2]]
"""
# BEGIN PROBLEM 9
new_list = []
for i in range(len(times_per_player)):
temp_list = []
for j in range((len(times_per_player[i]) - 1)):
temp_list += [times_per_player[i][j+1] - times_per_player[i][j]]
new_list += [temp_list]
new_match = match(words, new_list)
return new_match
# END PROBLEM 9
def fastest_words(match):
"""Return a list of lists of which words each player typed fastest.
Arguments:
match: a match data abstraction as returned by time_per_word.
>>> p0 = [5, 1, 3]
>>> p1 = [4, 1, 6]
>>> fastest_words(match(['Just', 'have', 'fun'], [p0, p1]))
[['have', 'fun'], ['Just']]
>>> p0 # input lists should not be mutated
[5, 1, 3]
>>> p1
[4, 1, 6]
"""
player_indices = range(len(get_times(match))) # contains an *index* for each player
word_indices = range(len(get_words(match))) # contains an *index* for each word
play_times_list = get_times(match)
words_list = get_words(match)
# BEGIN PROBLEM 10
fastest = [[] for _ in player_indices]
for i in word_indices:
min_index = 0
min_value = min(get_times(match), key = lambda x: x[i])
for j in player_indices:
if play_times_list[j] == min_value:
fastest[j].append(word_at(match, i))
break
return fastest
# END PROBLEM 10
def match(words, times):
"""A data abstraction containing all words typed and their times.
Arguments:
words: A list of strings, each string representing a word typed.
times: A list of lists for how long it took for each player to type
each word.
times[i][j] = time it took for player i to type words[j].
Example input:
words: ['Hello', 'world']
times: [[5, 1], [4, 2]]
"""
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(match, word_index):
"""A selector function that gets the word with index word_index"""
assert 0 <= word_index < len(match[0]), "word_index out of range of words"
return match[0][word_index]
def get_words(match):
"""A selector function for all the words in the match"""
return match[0]
def get_times(match):
"""A selector function for all typing times for all players"""
return match[1]
def time(match, 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(match[0]), "word_index out of range of words"
assert player_num < len(match[1]), "player_num out of range of players"
return match[1][player_num][word_index]
def match_string(match):
"""A helper function that takes in a match object and returns a string representation of it"""
return "match(%s, %s)" % (match[0], match[1])
enable_multiplayer = False # Change to True when you're ready to race.
##########################
# 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)