-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_helpers.py
431 lines (372 loc) · 13.7 KB
/
example_helpers.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
import os
import contextlib
def suppress_stdout(func):
def wrapper(*a, **ka):
with open(os.devnull, 'w') as devnull:
with contextlib.redirect_stdout(devnull):
return func(*a, **ka)
return wrapper
def check_combo(input_op, input_1, input_2):
"""
A function to print the various results of different arithmetic operator
input combinations on two input types.
Args:
input_op: A string representation of a input type
input_1: A numeric type to test
input_2: A numeric type to test
"""
# Note we dont raise exceptions as we want to see and print the exception
# later, normally this would be bad
# practice.
import numbers
if type(input_1) is type(input_2):
print("Warning: input types are not different\
this test will be very dull")
for i in (input_1, input_2):
if not isinstance(i, numbers.Number):
print("Warning, datatype is not numeric")
import operator
ops = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
'%': operator.mod,
'**': operator.pow,
'//': operator.floordiv,
}
input_combos = [
(input_1, input_1),
(input_2, input_2),
(input_1, input_2),
(input_2, input_1)
]
for i1, i2 in input_combos:
try:
my_tmp = ops[input_op](i1, i2)
my_tmp_type = f"type {type(my_tmp)}"
except Exception as e:
exception_cause = f"{ e.__class__ }"
my_tmp_type = f" { exception_cause[8:-2]}: {e}"
print(f"type {type(i1)} {input_op} type {type(i2)}, \
yields {my_tmp_type}")
def check_fizzbuzz(input_fizzbuzz, fizzbuzz_size=20):
correct = True
for i in range(0, len(input_fizzbuzz)):
if input_fizzbuzz[i] != fizzbuzz(i+1):
print(f"You have an error with fizzbuzz element {i}")
correct = False
break
if len(input_fizzbuzz) == fizzbuzz_size and correct:
print(f"Success the first {fizzbuzz_size} numbers \
fizzbuzzed are \n {input_fizzbuzz}")
elif correct:
print(f'You dont have all {fizzbuzz_size} \
elements you only submitted {len(input_fizzbuzz)}')
def fizzbuzz(number_to_fizzbuzz):
# check if the modulus of the number is 0 if it is its a multiple!
is_number_fizz = number_to_fizzbuzz % 3 == 0
is_number_buzz = number_to_fizzbuzz % 5 == 0
# if both multiples then we need to fizzbuzz
is_number_fizzbuzz = is_number_fizz and is_number_buzz
# Check fizzbuzz first
# Then use two elif conditionals to check fizz then buzz
# Finally use else to print the number if none of the conditionals pass.
if (is_number_fizzbuzz):
ret = 'fizzbuzz'
elif (is_number_fizz):
ret = 'fizz'
elif (is_number_buzz):
ret = 'buzz'
else:
ret = number_to_fizzbuzz
return ret
def check_fizz(input_fizz, fizz_size):
fizzed = [i if i % 3 else 'fizz' for i in range(1, 101)]
correct = True
for i in range(0, len(input_fizz)):
if input_fizz[i] != fizzed[i]:
print(f"You have an error with fizzed element {i}")
correct = False
break
if len(input_fizz) == fizz_size and correct:
print(f"Success the first {fizz_size} \
numbers fizzed are \n {input_fizz}")
elif correct:
print(f'You dont have all {fizz_size}\
elements you only submitted {len(input_fizz)}')
def check_buzz(input_buzz, buzz_size):
buzzed = [i if i % 5 else 'buzz' for i in range(1, 101)]
correct = True
for i in range(0, len(input_buzz)):
if input_buzz[i] != buzzed[i]:
print(f"You have an error with buzzed element {i}")
correct = False
break
if len(input_buzz) == buzz_size and correct:
print(f"Success the first {buzz_size}\
numbers buzzed are \n {input_buzz}")
elif correct:
print(f'You dont have all {buzz_size}\
elements you only submitted {len(input_buzz)}')
def check_1_2_boo(fn_to_check):
fn_no_stdout = suppress_stdout(fn_to_check)
out1 = fn_no_stdout(1)
out2 = fn_no_stdout(2)
out3 = fn_no_stdout(3)
message = "Your function:\n"
if out1 != "1":
message += "Produces the wrong output for input of 1\n"
else:
message += "Is correct for input of 1\n"
if out2 != "2":
message += "Produces the wrong output for input of 2\n"
else:
message += "Is correct for input of 2\n"
if out3 != "boo":
message += "Produces the wrong output for input that isn't 1 or 2\n"
else:
message += "Is correct for inputs that are not 1 or 2\n"
print(message)
def check_functions(fizz_fun, buzz_fun, fizzbuzz_fun):
numbers_to_check = [1, 100, 3, 9, 5, 10, 15, 45]
number_failed = 0
# Test Fizz
for test_num in numbers_to_check:
correct_ans = fizzbuzz(test_num) == "fizz"
if fizz_fun(test_num) != correct_ans:
print("check_fizz failed with input:", test_num)
number_failed += 1
# Test Buzz
for test_num in numbers_to_check:
correct_ans = fizzbuzz(test_num) == "buzz"
if buzz_fun(test_num) != correct_ans:
print("check_buzz failed with input:", test_num)
number_failed += 1
# Test Fizzbuzz
for test_num in numbers_to_check:
correct_ans = fizzbuzz(test_num) == "fizzbuzz"
if fizzbuzz_fun(test_num) != correct_ans:
print("check_fizzbuzz failed with input:", test_num)
number_failed += 1
print(f'Tests Complete: {24-number_failed} Tests Passed,\
{number_failed} Tests Failed')
def keyword_check_fizz(
number_to_check: int,
fizz_num: int = 3,
buzz_num: int = 5) -> bool:
""" This function checks if a number is fizz but not buzz,
i.e. number is a multiple of 3 but not 5, and returns True if it is.
Parameters
----------
number_to_check : int
input integer to check for fizz
fizz_num : int
input integer to use for fizz check
buzz_num : int
input integer to use for buzz check
Returns
-------
bool
True if number passes fizz check but not buzz check.
"""
if number_to_check % fizz_num == 0:
output = True
else:
output = False
if number_to_check % buzz_num == 0:
output = False
return output
def keyword_check_buzz(
number_to_check: int,
fizz_num: int = 3,
buzz_num: int = 5) -> bool:
""" This function checks if a number is fizz but not buzz, i.e. number is
a multiple of 3 but not 5, and returns True if it is.
Parameters
----------
number_to_check : int
input integer to check for fizz
fizz_num : int
input integer to use for fizz check
buzz_num : int
input integer to use for buzz check
Returns
-------
bool
True if number passes buzz check but not fizz check.
"""
if number_to_check % buzz_num == 0:
output = True
else:
output = False
if number_to_check % fizz_num == 0:
output = False
return output
def keyword_check_fizzbuzz(
number_to_check: int,
fizz_num: int = 3,
buzz_num: int = 5) -> bool:
""" This function checks if a number is fizz but not buzz,
i.e. number is a multiple of 3 but not 5, and returns True if it is.
Parameters
----------
number_to_check : int
input integer to check for fizz
fizz_num : int
input integer to use for fizz check
buzz_num : int
input integer to use for buzz check
Returns
-------
bool
True if number passes fizz and buzz check.
"""
if number_to_check % fizz_num == 0:
output = True
else:
output = False
if output and (number_to_check % buzz_num == 0):
output = True
else:
output = False
return output
def keyword_fizzbuzz(
list_to_mutate: list,
fizz_num: int = 3,
buzz_num: int = 5,
fizz_word: str = 'fizz',
buzz_word: str = 'buzz') -> None:
""" This function takes a list of numbers and mutates it to replace
numbers that are multiples of fizz_num with fizz_word, multiples of
buzz_num with buzz_word, and multiples of fizz_num*buzz_num with
fizz_word+buzz_word.
Parameters
----------
list_to_mutate : list
input list of numbers to mutate
fizz_num : int
input integer to use for fizz check
buzz_num : int
input integer to use for buzz check
Returns
-------
None
This function does not return anything,
but mutates the list_to_mutate in place.
"""
for i in range(len(list_to_mutate)):
if keyword_check_fizzbuzz(
list_to_mutate[i],
fizz_num=fizz_num,
buzz_num=buzz_num):
list_to_mutate[i] = fizz_word + buzz_word
elif keyword_check_fizz(
list_to_mutate[i],
fizz_num=fizz_num,
buzz_num=buzz_num):
list_to_mutate[i] = fizz_word
elif keyword_check_buzz(
list_to_mutate[i],
fizz_num=fizz_num,
buzz_num=buzz_num):
list_to_mutate[i] = buzz_word
def check_keyword_fizzbuzz(learner_function):
""" This function checks if a function is
correct for the keyword_fizzbuzz function.
Parameters
----------
learner_function : function
input function to check for correctness
Returns
-------
None
This function does not return anything, but prints out a message
indicating if the function is correct or not.
"""
test_list = [i for i in range(1, 101)]
correct_list = [i for i in range(1, 101)]
print("Testing your function with the default values.")
keyword_fizzbuzz(correct_list)
learner_function(test_list)
if test_list == correct_list:
print("Your function is correct when using the default values.")
else:
print("Your function is not correct when using the default values.\
Please try again.")
print("Testing your function with different\
values for fizz_num and buzz_num.")
test_list = [i for i in range(1, 101)]
correct_list = [i for i in range(1, 101)]
keyword_fizzbuzz(correct_list, fizz_num=4, buzz_num=7)
learner_function(test_list, fizz_num=4, buzz_num=7)
if test_list == correct_list:
print("Your function is correct when using different values\
for fizz_num and buzz_num.")
else:
print("Your function is not correct when using different values\
for fizz_num and buzz_num. Please try again.")
print("Testing your function with different values\
for fizz_word and buzz_word.")
test_list = [i for i in range(1, 101)]
correct_list = [i for i in range(1, 101)]
keyword_fizzbuzz(correct_list, fizz_word='whizz', buzz_word='bang')
learner_function(test_list, fizz_word='whizz', buzz_word='bang')
if test_list == correct_list:
print("Your function is correct when using different values\
for fizz_word and buzz_word.")
else:
print("Your function is not correct when using different values\
for fizz_word and buzz_word. Please try again.")
def check_formatted_lorem():
# This function checks if the formatted lorem ipsum file is correct.
# First get the correct formatted lorem ipsum file.
with open('lorem_ipsum.txt', 'r') as f:
formatted_lines = []
for line in f:
words_in_line = line.split()
current_line_length = 0
for word in words_in_line:
if current_line_length+len(word)+1 < 90:
formatted_lines.append(word)
formatted_lines.append(" ")
else:
formatted_lines.append("\n")
current_line_length = 0
formatted_lines.append(word)
formatted_lines.append(" ")
current_line_length += len(word) + 1
# We will always have a trailing space but instead we want a double newline to indicate the end of a paragraph.
# Instead of removing the trailing space we will just replace the last list element with a double newline.
formatted_lines[-1] = "\n\n"
with open('lorem_ipsum_formatted_sol.txt', 'w') as f:
f.writelines(formatted_lines)
with open('lorem_ipsum_formatted_sol.txt', 'r') as f:
formatted_lines = f.readlines()
# Now get the learner's formatted lorem ipsum file.
with open('lorem_ipsum_formatted.txt', 'r') as f:
learner_lines = f.readlines()
length_error_line = []
correct_lines_with_paragraphs = []
for line_num, line in enumerate(learner_lines):
line_length = len(line)
paragraph_count = line.count("\n\n")
if line_length > 90:
length_error_line.append(line_num)
for line_num, line in enumerate(formatted_lines):
paragraph_count = line.count("\n\n")
if paragraph_count == 1:
correct_lines_with_paragraphs.append(line_num)
# Print the errors.
if len(length_error_line) > 0:
print(f"The following lines are too long: {length_error_line}")
else:
print("All lines are the correct length.")
# Now check if the two files are the same.
if formatted_lines != learner_lines:
for i, (sol, sub) in enumerate(zip(formatted_lines, learner_lines)):
if sol != sub:
print("Line", i, "is different to the given solution.")
return
else:
print("Your formatted lorem ipsum file is perfect.")