-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathceai_python_aula03.py
More file actions
394 lines (338 loc) · 17 KB
/
ceai_python_aula03.py
File metadata and controls
394 lines (338 loc) · 17 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
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
""" Este módulo deve ser utilizado com a aula 3 do curso de python """
import functools
from inspect import signature
import operator
import copy
import traceback
import html
class ClasseExemplo_01:
def atribui_valor(self, x):
self._valor = x
def recupera_valor(self):
return self._valor
def __str__(self):
return str(self._valor)
class SolucaoResultado():
def __init__(self, res=True, ex=None):
self._res = res
self._ex = ex
def __str__(self):
if self._res:
return "Resultado Correto"
if self._ex is not None:
return "Resultado Incorreto: " + str(ex)
return "Resultado Incorreto"
def __bool__(self):
return self._res
def _repr_html_(self):
if self._res:
return '<div style="border-style:solid;border-color:green">Exercício Correto!</div>'
else:
if self._ex:
if self._ex.__cause__:
cause = ''.join(traceback.format_exception(type(self._ex.__cause__),self._ex.__cause__,self._ex.__cause__.__traceback__))
msg = '<div style="border-style:solid;border-color:red">Exercício Incorreto!<br/>{0}<br/>Exceção Causadora:<br/><pre>{1}</pre></div>'.format(html.escape(self._ex.formatted_message()),html.escape(cause))
else:
msg = '<div style="border-style:solid;border-color:red">Exercício Incorreto!<br/>{0}</div>'.format(html.escape(self._ex.formatted_message()))
else:
msg = "Exercício Incorreto"
return msg
class SolucaoInvalida(BaseException):
def __init__(self, *args):
if args:
self._message = args[0]
else:
self._message = None
def formatted_message(self):
return self._message
def __str__(self):
print('calling str')
if self._message:
return 'SolucaoInvalida, {0} '.format(self._message)
else:
return 'SolucaoInvalida'
def VerificaAmbiente():
print("Ambiente inicializado com sucesso")
return True
def valida_ex_01_01(a):
try:
gabarito = [5.0, 7.5, 0.0]
if type(a)!=list:
raise SolucaoInvalida("O tipo de dado esperado é uma lista. O passado foi: " + str(type(a)))
if len(a) != len(gabarito):
raise SolucaoInvalida("O tamanho esperado da lista é " + str(len(gabarito)) + ". O passado foi:" +str(len(a)))
for i in range(len(a)):
if type(a[i]) != type(gabarito[i]):
raise SolucaoInvalida("O elemento na posição " + str(i) + " deveria ser do tipo " + str(type(gabarito[i])) + ". O tipo real é " + str(type(a[i])))
if a[i] != gabarito[i]:
raise SolucaoInvalida("O elemento na posição " + str(i) + " deveria ter o valor " + str(gabarito[i]) + ". O valor real é " + str(a[i]))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_01_02(a):
try:
gabarito = [[1.0, 3.0], [2.0, 6.0], [4.0, 12.0]]
if type(a)!=list:
raise SolucaoInvalida("O tipo de dado esperado é uma lista. O passado foi: " + str(type(a)))
if len(a) != len(gabarito):
raise SolucaoInvalida("O tamanho esperado da lista é " + str(len(gabarito)) + ". O passado foi:" +str(len(a)))
for i in range(len(a)):
if type(a[i]) != type(gabarito[i]):
raise SolucaoInvalida("A linha " + str(i) + " deveria ser do tipo " + str(type(gabarito[i])) + ". O tipo real é " + str(type(a[i])))
if len(a[i]) != len(gabarito[i]):
raise SolucaoInvalida("A linha " + str(i) + " deveria ter comprimento " + str(len(gabarito[i])) + ". O comprimento real é " + str(len(a[i])))
for j in range(len(a[i])):
if type(a[i][j]) != type(gabarito[i][j]):
raise SolucaoInvalida("O elemento na posição (" + str(i) + "," + str(j) + ") deveria ser do tipo " + str(type(gabarito[i][j])) + ". O tipo real é " + str(type(a[i][j])))
if a[i][j] != gabarito[i][j]:
raise SolucaoInvalida("O elemento na posição (" + str(i) + "," + str(j) + ") deveria ter o valor " + str(gabarito[i][j]) + ". O valor real é " + str(a[i][j]))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_01_03(func):
def testa(arg):
try:
_arg = copy.deepcopy(arg)
ret = func(arg)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu o parâmetro " + str(arg)) from ex
if type(ret)!=bool:
raise SolucaoInvalida("A função retornou um valor do tipo" + str(type(ret)) + " quando deveria ter retornado um bool")
if arg!=_arg:
raise SolucaoInvalida("A função não deve alterar os argumentos passados a ela")
return ret
try:
if len(signature(func).parameters)!=1:
raise SolucaoInvalida("A função deve aceitar exatamente um parâmetro")
if testa(1):
raise SolucaoInvalida("A função aceitou um número, deveria aceitar somente listas")
if testa((1,)):
raise SolucaoInvalida("A função aceitou uma tupla, deveria aceitar somente listas")
if testa(((1,),)):
raise SolucaoInvalida("A função aceitou uma tupla, deveria aceitar somente listas")
if testa([]):
raise SolucaoInvalida("A função aceitou uma lista nula")
if testa([(1.0)]):
raise SolucaoInvalida("A função aceitou uma lista cujo primeiro elemento não é uma lista")
if testa([[1.0], (2.0)]):
raise SolucaoInvalida("A função aceitou uma lista cujo segundo elemento não é uma lista")
if testa([[1.0], (2.0)]):
raise SolucaoInvalida("A função aceitou uma lista contendo um elemento que não é uma lista")
if testa([[int(1)], [2.0]]) or testa([[1.0], [int(2)]]):
raise SolucaoInvalida("A função aceitou uma entrada que contém um valor que não é um float")
if testa([[1.0], [2.0, 3.0]]) or testa([[1.0, 2.0], [3.0]]):
raise SolucaoInvalida("A função aceitou uma entrada com linhas de tamanhos diferentes")
if testa([[]]):
raise SolucaoInvalida("A função aceitou uma entrada que contém uma subsequência nula")
testes_pos = [[[0.0]], [[1.0],[2.0]], [[1.0, 2.0]], [[1.0, 2.0],[3.0,4.0]],[[1.0, 2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]]]
for pos in testes_pos:
if not testa(pos):
raise SolucaoInvalida("A função rejeitou a entrada "+ str(pos))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def _inner(v1, v2):
return functools.reduce(operator.add, (a*b for a, b in zip(v1,v2)))
def _sumvv(v1, v2):
return [x+y for x, y in zip(v1, v2)]
def _multev(v, a):
return [x*a for x in v]
def _diff(v1, v2):
v3 = _multev(v2, -1.0)
v4 = _sumvv(v1, v3)
m = _inner(v4, v4)
return m
def _diffmm(m1,m2):
return functools.reduce(operator.add, (_diff(l1, l2) for l1, l2 in zip(m1,m2)))
def _summm(m1, m2):
return[ [x+y for x, y in zip(l1, l2)] for l1, l2 in zip(m1, m2)]
def _ttm(m):
return [ [ m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
def _prodmv(m, v):
return [ _inner(x, v) for x in m]
def _prodmm(m1, m2):
return [[functools.reduce(operator.add, (l[k]*m2[k][j] for k in range(len(l)))) for j in range(len(m2[0]))] for l in m1]
def _validavv(m, l):
if type(m)!=list:
raise SolucaoInvalida("A função retornou um valor do tipo" + str(type(m)) + " quando deveria ter retornado uma lista")
if len(m)!=l:
raise SolucaoInvalida("A função retornou uma lista com comprimento " + str(len(m)) + " quando deveria ter retornado uma lista com comprimento " + str(l))
def _validamm(m, l, r):
if type(m)!=list:
raise SolucaoInvalida("A função retornou um valor do tipo" + str(type(m)) + " quando deveria ter retornado uma lista")
if len(m)!=l:
raise SolucaoInvalida("A função retornou uma lista com comprimento " + str(len(m)) + " quando deveria ter retornado uma lista com comprimento " + str(l))
for linha in m:
if type(linha)!=list:
raise SolucaoInvalida("O resultado da função contém uma linha que não é uma lista")
if len(linha)!=r:
raise SolucaoInvalida("O resultado da função contém uma linha de comprimento "+ str(len(linha)) +". Todas as linhas deveriam ter comprimento " + str(r))
def valida_ex_02_01_01(func):
tests = (([1.0],[2.0]), ([1.0, -1.0], [1.0, 1.0]), ([1.0,1.0,1.0],[2.0,3.0,4.0]))
def testa(arg1, arg2):
_arg1 = copy.deepcopy(arg1)
_arg2 = copy.deepcopy(arg2)
try:
ret = func(arg1, arg2)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu os parâmetros " + str(arg1) + "e " + str(arg2)) from ex
if type(ret)!=list:
raise SolucaoInvalida("A função retornou um valor do tipo" + str(type(ret)) + " quando deveria ter retornado uma lista")
if len(ret)!=len(arg1):
raise SolucaoInvalida("A função retornou uma lista com comprimento " + str(len(ret)) + " quando deveria ter retornado uma lista com comprimento " + str(len(arg1)))
if arg1!=_arg1 or arg2!=_arg2:
raise SolucaoInvalida("A função não deve alterar os argumentos passados a ela")
return ret
try:
if len(signature(func).parameters)!=2:
raise SolucaoInvalida("A função deve aceitar exatamente dois parâmetros")
for (v1, v2) in tests:
r = testa(v1,v2)
g = _sumvv(v1,v2)
if _diff(r, g) > 0.00001:
raise SolucaoInvalida("A função retornou " + str(r) + " para entradas x=" + str(v1) + " e y=" +str(v2) + " (o resultado esperado era "+ str(g)+")")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_02_02_01(func):
tests = (([[1.0]],[[2.0]]), ([[1.0, -1.0]], [[1.0, 1.0]]), ([[1.0],[1.0],[1.0]],[[2.0],[3.0],[4.0]]),([[1,2],[3,4]],[[-1,2],[1,3]]))
def testa(arg1, arg2):
_arg1 = copy.deepcopy(arg1)
_arg2 = copy.deepcopy(arg2)
try:
ret = func(arg1, arg2)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu os parâmetros " + str(arg1) + "e " + str(arg2)) from ex
_validamm(ret, len(arg1),len(arg1[0]))
if arg1!=_arg1 or arg2!=_arg2:
raise SolucaoInvalida("A função não deve alterar os argumentos passados a ela")
return ret
try:
if len(signature(func).parameters)!=2:
raise SolucaoInvalida("A função deve aceitar exatamente dois parâmetros")
for (m1, m2) in tests:
r = testa(m1,m2)
g = _summm(m1,m2)
if _diffmm(r, g) > 0.00001:
raise SolucaoInvalida("A função retornou " + str(r) + " para entradas x=" + str(m1) + " e y=" +str(m2) + " (o resultado esperado era "+ str(g)+")")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_02_03_01(func):
tests = ([[1.0]], [[1.0, -1.0]], [[1.0],[1.0],[1.0]],[[1,2],[3,4]],[[-1,2],[1,3]])
def testa(arg1):
try:
ret = func(arg1)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu o parâmetro " + str(arg1)) from ex
_validamm(ret, len(arg1[0]),len(arg1))
return ret
try:
if len(signature(func).parameters)!=1:
raise SolucaoInvalida("A função deve aceitar exatamente um parâmetro")
for m in tests:
r = testa(m)
g = _ttm(m)
if _diffmm(r, g) > 0.00001:
raise SolucaoInvalida("A função retornou " + str(r) + " para entrada " + str(m1) + " (o resultado esperado era "+ str(g)+")")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_02_04_01(func):
tests = (([1.0], 2.0), ([1.0],-1.0),([1.0,2.0,3.0],1.0),([-1.0,1.25,2.0,3.0],1.5))
def testa(arg1, arg2):
_arg1 = copy.deepcopy(arg1)
try:
ret = func(arg1, arg2)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu os parâmetros " + str(arg1) + "e " + str(arg2)) from ex
_validavv(ret, len(arg1))
if _arg1 != arg1:
raise SolucaoInvalida("A função não deve alterar os argumentos passados a ela")
return ret
try:
if len(signature(func).parameters)!=2:
raise SolucaoInvalida("A função deve aceitar exatamente dois parâmetros")
for v, a in tests:
r = testa(v, a)
g = _multev(v, a)
if _diff(r, g) > 0.00001:
raise SolucaoInvalida("A função retornou " + str(r) + " para entrada x=" + str(v) + " a=" + str(a) + " (o resultado esperado era "+ str(g)+")")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_02_05_01(func):
tests = (([1.0], [2.0]), ([0.7071067811865476, 0.7071067811865476],[-0.7071067811865476,0.7071067811865476]),([1.0,2.0,3.0],[1.0,1.0,1.0]))
def testa(arg1, arg2):
_arg1 = copy.deepcopy(arg1)
_arg2 = copy.deepcopy(arg2)
try:
ret = func(arg1, arg2)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu os parâmetros " + str(arg1) + "e " + str(arg2)) from ex
if type(ret)!=float:
raise SolucaoInvalida("A função deve retornar um float")
if _arg1 != arg1 or _arg2 != arg2:
raise SolucaoInvalida("A função não deve alterar os argumentos passados a ela")
return ret
try:
if len(signature(func).parameters)!=2:
raise SolucaoInvalida("A função deve aceitar exatamente dois parâmetros")
for v1, v2 in tests:
r = testa(v1, v2)
g = _inner(v1, v2)
if abs(r-g) > 0.00001:
raise SolucaoInvalida("A função retornou " + str(r) + " para entrada x=" + str(v1) + " y=" + str(v2) + " (o resultado esperado era "+ str(g)+")")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_02_06_01(func):
tests = (([[1.0]], [2.0]), ([[1.0],[2.0]],[-1.0]),([[1.0,0.5],[0.5,1.0]],[1.0,2.0]))
def testa(arg1, arg2):
_arg1 = copy.deepcopy(arg1)
_arg2 = copy.deepcopy(arg2)
try:
ret = func(arg1, arg2)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu os parâmetros " + str(arg1) + "e " + str(arg2)) from ex
_validavv(ret, len(_arg1))
if _arg1 != arg1 or _arg2 != arg2:
raise SolucaoInvalida("A função não deve alterar os argumentos passados a ela")
return ret
try:
if len(signature(func).parameters)!=2:
raise SolucaoInvalida("A função deve aceitar exatamente dois parâmetros")
for m, v in tests:
r = testa(m, v)
g = _prodmv(m, v)
if _diff(r,g) > 0.00001:
raise SolucaoInvalida("A função retornou " + str(r) + " para entrada m=" + str(m) + " x=" + str(v) + " (o resultado esperado era "+ str(g)+")")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_02_07_01(func):
tests = (([[1.0]], [[2.0]]), ([[1.0],[2.0]],[[-1.0,-2.0]]),([[1.0,0.5],[0.5,1.0]],[[1.0,2.0],[0.5,1.0]]))
def testa(arg1, arg2):
_arg1 = copy.deepcopy(arg1)
_arg2 = copy.deepcopy(arg2)
try:
ret = func(arg1, arg2)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu os parâmetros " + str(arg1) + "e " + str(arg2)) from ex
_validamm(ret, len(_arg1), len(_arg2[0]))
if _arg1 != arg1 or _arg2 != arg2:
raise SolucaoInvalida("A função não deve alterar os argumentos passados a ela")
return ret
try:
if len(signature(func).parameters)!=2:
raise SolucaoInvalida("A função deve aceitar exatamente dois parâmetros")
for m1, m2 in tests:
r = testa(m1, m2)
g = _prodmm(m1, m2)
if _diffmm(r,g) > 0.00001:
raise SolucaoInvalida("A função retornou " + str(r) + " para entrada x=" + str(m1) + " y=" + str(m2) + " (o resultado esperado era "+ str(g)+")")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
if __name__ != 'main':
VerificaAmbiente()