-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathceai_python_aula05.py
More file actions
171 lines (153 loc) · 7.12 KB
/
ceai_python_aula05.py
File metadata and controls
171 lines (153 loc) · 7.12 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
""" Este módulo deve ser utilizado com a aula 5 do curso de python """
import functools
from inspect import signature
from inspect import getsource
import operator
import copy
import traceback
import html
import itertools
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(func):
def testa(arg):
try:
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 ret is None:
raise SolucaoInvalida("A função não retornou nenhum valor")
return ret
try:
if type(func)!=type(valida_ex_01_01):
raise SolucaoInvalida("Você deve passar uma função")
if len(signature(func).parameters)!=1:
raise SolucaoInvalida("A função deve aceitar exatamente um parâmetro")
listas = [[1,2,3,4], ['a', 'b', 'c'], [0.1, 0.0, 0.2]]
valores = [1, 'b', 0.0]
for valor in valores:
f = func(valor)
if type(f)!=type(valida_ex_01_01):
raise SolucaoInvalida("A função não retornou uma nova função quando recebeu o parâmetro " + str(valor))
if len(signature(f).parameters)!=1:
raise SolucaoInvalida("A nova função retornada deve aceitar exatamente um parâmetro")
for lista in listas:
try:
ret = f(lista)
except Exception as ex:
raise SolucaoInvalida("A nova função, gerada com o argumento " + str(valor) + " lançou uma exceção quando recebeu o parâmetro " + str(lista)) from ex
if ret is None:
raise SolucaoInvalida("A nova função, gerada com o argumento " + str(valor) + " não retornou nenhum valor quando recebeu o parâmetro " + str(lista))
if type(ret) != bool:
raise SolucaoInvalida("A nova função, gerada com o argumento " + str(valor) + " não retornou um booleano valor quando recebeu o parâmetro " + str(lista))
gab = valor in lista
if ret != gab:
raise SolucaoInvalida("A nova função, gerada com o argumento " + str(valor) + " retornou " + str(ret) + " quando recebeu o parâmetro " + str(lista) + ". O valor esperado era " + str(gab))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_01_02_01(func):
def testa(arg1, arg2):
try:
ret = func(arg1, arg2)
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção quando recebeu o parâmetros " + str(arg1) + " e " + str(arg2)) from ex
if ret is None:
raise SolucaoInvalida("A função não retornou nenhum valor")
return ret
try:
if type(func)!=type(valida_ex_01_02_01):
raise SolucaoInvalida("Você deve passar uma função")
if func.__name__!='<lambda>':
raise SolucaoInvalida("Sua função deve ser declarada por uma expressão lambda")
if len(signature(func).parameters)!=2:
raise SolucaoInvalida("A função deve aceitar exatamente dois parâmetros")
vx = [-3, -2, -1, 0, 1, 2 ,3]
for v1, v2 in itertools.product(vx, vx):
ret = testa(v1, v2)
gab = v1 if v1 > v2 else v2
if ret != gab:
raise SolucaoInvalida("A função retornou " + str(ret) + " quando recebeu os parâmetros " + str(v1) + ", " + str(v2) + ". O valor esperado era " + str(gab))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_02_01_01(func):
def testa(arg1, 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(arg)) from ex
if ret is None:
raise SolucaoInvalida("A função não retornou nenhum valor")
if type(ret)!=list:
raise SolucaoInvalida("A função não retornou uma sequência")
return ret
try:
if type(func)!=type(valida_ex_01_02_01):
raise SolucaoInvalida("Você deve passar uma função")
if len(signature(func).parameters)!=2:
raise SolucaoInvalida("A função deve aceitar exatamente dois parâmetros")
try:
source = getsource(func)
except TypeError:
raise SolucaoInvalida("A sua função deve ser composta da declaração e apenas uma linha de código")
lines = source.split('\n')
lcount = 0
for l in lines:
ll = l.lstrip()
if len(ll)==0 or ll.startswith('#') or ll.startswith('""""'):
continue
lcount += 1
if lcount > 2:
raise SolucaoInvalida("A sua função deve ser composta da declaração e apenas uma linha de código"+str(lcount))
vx = [(0,0), (3,2), (5, 2)]
for n, x in vx:
ret = testa(n, x)
gab = [i*x for i in range(n)]
if ret != gab:
raise SolucaoInvalida("A função retornou " + str(ret) + " quando recebeu os parâmetros " + str(n) + ", " + str(x) + ". O valor esperado era " + str(gab))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
if __name__ != 'main':
VerificaAmbiente()