-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathceai_python_aula08.py
More file actions
290 lines (256 loc) · 11.6 KB
/
ceai_python_aula08.py
File metadata and controls
290 lines (256 loc) · 11.6 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
""" Este módulo deve ser utilizado com a aula 8 do curso de python """
import functools
from inspect import signature
from inspect import getsource
import operator
import copy
import traceback
import html
import itertools
import sys
import pathlib
import os
import re
import json
import datetime
import numpy
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_08_01_01(matriz):
try:
if type(matriz)!=numpy.ndarray:
raise SolucaoInvalida("O objeto passado não é do tipo numpy.array")
if matriz.ndim!=2:
raise SolucaoInvalida("O objeto passado não é de duas dimensões")
if matriz.shape != (2,3):
raise SolucaoInvalida("As dimensões do objeto são inválidas")
for i in range(2):
for j in range(3):
if matriz[i,j]!=3*i+j:
raise SolucaoInvalida("O coeficiente em "+str(i)+","+str(j)+" tem valor " + str(matriz[i,j]) + ". O valor esperado era " + str(3*i+j));
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_08_01_02(matriz):
try:
if type(matriz)!=numpy.ndarray:
raise SolucaoInvalida("O objeto passado não é do tipo numpy.array")
if matriz.ndim!=2:
raise SolucaoInvalida("O objeto passado não é de duas dimensões")
if matriz.shape != (20,50):
raise SolucaoInvalida("As dimensões do objeto são inválidas")
for i in range(20):
for j in range(50):
if matriz[i,j]!=0:
raise SolucaoInvalida("O coeficiente em "+str(i)+","+str(j)+" tem valor " + str(matriz[i,j]) + ". O valor esperado era 0");
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_08_01_03(vetor):
try:
if type(vetor)!=numpy.ndarray:
raise SolucaoInvalida("O objeto passado não é do tipo numpy.array")
if vetor.ndim!=1:
raise SolucaoInvalida("O objeto passado não é de uma dimensão")
if vetor.shape != (1000,):
raise SolucaoInvalida("As dimensões do objeto são inválidas")
for i in range(1000):
if abs(vetor[i]-(i/10))>0.0001:
raise SolucaoInvalida("O coeficiente em "+str(i)+" tem valor " + str(vetor[i]) + ". O valor esperado era " + str(i/10));
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_08_02_01(vetors, vetorc):
try:
if type(vetors)!=numpy.ndarray:
raise SolucaoInvalida("O primeiro objeto passado não é do tipo numpy.array")
if type(vetorc)!=numpy.ndarray:
raise SolucaoInvalida("O segundo objeto passado não é do tipo numpy.array")
if vetors.ndim!=1:
raise SolucaoInvalida("O primeiro objeto passado não é de uma dimensão")
if vetorc.ndim!=1:
raise SolucaoInvalida("O segundo objeto passado não é de uma dimensão")
if vetors.shape != (1257,):
raise SolucaoInvalida("As dimensões do primeiro objeto são inválidas")
if vetorc.shape != (1257,):
raise SolucaoInvalida("As dimensões do segundo objeto são inválidas")
for i in range(1257):
x = 2*numpy.pi*i/1257
s = numpy.sin(x)
c = numpy.cos(x)
if abs(vetors[i]-s)>0.01:
raise SolucaoInvalida("O coeficiente em "+str(i)+" tem valor " + str(vetors[i]) + ". O valor esperado era " + str(s));
if abs(vetorc[i]-c)>0.01:
raise SolucaoInvalida("O coeficiente em "+str(i)+" tem valor " + str(vetorc[i]) + ". O valor esperado era " + str(c));
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_01_01_02():
try:
if 'test01' not in sys.modules:
raise SolucaoInvalida("O módulo test01 não foi importado")
if not sys.modules['test01'].test_it():
raise SolucaoInvalida("A função minha_funcao() não foi chamada")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_01_02_01(func):
try:
if not pathlib.Path('/content/gdrive/My Drive/cursoai_exercicios').is_dir():
raise SolucaoInvalida("O diretório não foi criado!")
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_05_01_01(linhas):
try:
if type(linhas)!=list:
raise SolucaoInvalida("Você deve passar uma sequência")
arquivo = open("/content/gdrive/My Drive/cursoai_python_aula_03/dados/dados01.txt")
linhas_gab = arquivo.readlines()
if len(linhas)!=len(linhas_gab):
raise SolucaoInvalida("Você passou um número incorreto de linhas")
for i in range(len(linhas)):
if linhas[i]!=linhas_gab[i]:
raise SolucaoInvalida("A linha " + str(i) + " contém " + linhas[i] + " mas deveria conter " + linhas_gab[i])
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_05_01_02(linha):
try:
if type(linha)!=str:
raise SolucaoInvalida("Você deve passar uma string")
if linha != 'parametro_01 = 2\n':
raise SolucaoInvalida("Conteúdo errado, você passou " + str(linha))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_05_01_03():
try:
if not pathlib.Path('/content/resultado.txt').is_file():
raise SolucaoInvalida("O arquivo não existe")
file = open('/content/resultado.txt', 'rt')
linhas = file.readlines()
if len(linhas)!=10:
raise SolucaoInvalida("O arquivo tem "+str(len(linhas))+ " e deveria ter 10 linhas.")
for i in range(10):
try:
if int(linhas[i])!=((i+1)*(i+1)):
raise SolucaoInvalida("A linha " + str(i+1) + " contém " + linhas[i] + " e deveria conter " + str((i+1)*(i+1)))
except ValueError:
raise SolucaoInvalida("A linha " + str(i+1) + " contém " + linhas[i] + " e deveria conter " + str((i+1)*(i+1)))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_05_02_01():
try:
if not pathlib.Path('/content/resultado.json').is_file():
raise SolucaoInvalida("O arquivo não existe")
file = open('/content/resultado.json', 'rt')
conteudo = file.read()
if len(conteudo)==0:
raise SolucaoInvalida("O arquivo está vazio.")
try:
obj = json.loads(conteudo)
except json.JSONDecodeError as err:
raise SolucaoInvalida("Não foi possível decodificar o conteúdo JSON do arquivo.") from err
if type(obj)!= dict:
raise SolucaoInvalida("O objeto armazenado não é um dicionário.") from err
chaves = []
for chave in obj:
try:
i = int(chave)
except ValueError as err:
raise SolucaoInvalida("A chave " + chave + " não é um inteiro válido!") from err
if i<1 or i > 100:
raise SolucaoInvalida("A chave " + str(i) + " está fora do alcance especificado!")
valor = obj[chave]
if type(valor)!=int:
raise SolucaoInvalida("O valor " + str(valor) + " não é um inteiro!")
if valor != i*i:
raise SolucaoInvalida("O valor " + str(valor) + " armazenado sob a chave " + chave + "está incorreto!")
chaves.append(i)
for i in range(1, 101):
if i not in chaves:
raise SolucaoInvalida("O dicionário não contém a chave " + str(i))
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
def valida_ex_05_03_01(func):
def testa():
try:
ret = func()
except Exception as ex:
raise SolucaoInvalida("A função lançou uma exceção") from ex
if ret is None:
raise SolucaoInvalida("A função não retornou nenhum valor")
if type(ret)!=str:
raise SolucaoInvalida("A função não retornou uma string")
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)!=0:
raise SolucaoInvalida("A função não deve aceitar parâmetros")
strdata_1 = testa()
agora_1 = datetime.datetime.utcnow()
try:
data_1 = datetime.datetime.strptime(strdata_1, "%Y-%m-%dT%H:%M:%S.%f-03:00") + datetime.timedelta(seconds=(3*60*60))
except ValueError as err:
raise SolucaoInvalida("A string não representa uma data válida") from err
strdata_2 = testa()
agora_2 = datetime.datetime.utcnow()
try:
data_2 = datetime.datetime.strptime(strdata_2, "%Y-%m-%dT%H:%M:%S.%f-03:00") + datetime.timedelta(seconds=(3*60*60))
except ValueError as err:
raise SolucaoInvalida("A string não representa uma data válida") from err
if abs((data_1 - agora_1).total_seconds()) > 60:
raise SolucaoInvalida("A hora " + str(data_1) + " não está correta")
if abs((data_2 - agora_2).total_seconds()) > 60:
raise SolucaoInvalida("A hora " + str(data_2) + " não está correta")
if (data_2-data_1).total_seconds() < 0:
raise SolucaoInvalida("A data " + str(data_2) + " foi retornada depois da " + str(data_2) )
except SolucaoInvalida as ex:
return SolucaoResultado(False, ex)
return SolucaoResultado()
if __name__ != 'main':
VerificaAmbiente()