Hi let's say that I want to replace a large el-ifs statement by a dictionary. A simplify version of this is as follows:
def functionA(a1, a2, a3):
results = {
'case1': a2/a3,
'case2': 1,
...
}
return results[a1]
so a1 would be a string ('case1' or 'case2' or ...) the problem is in some cases the a3 it maybe 0 so the results dictionary could not be define (in all those cases a1 would not be 'case1'). For instance:
functionA('case2', 1.0, 3.0)
Out[81]: 1
functionA('case2', 1.0, 0.0)
ZeroDivisionError: integer division or modulo by zero
So in the second case I expected 1 but I am getting an error.
A possible solution is:
def functionA(a1, a2, a3):
results = {
'case1': str(a2) + '/' + str(a3),
'case2': str(1),
}
return eval(results[a1])
Since I have a multiple cases with complex calculations, is there any better solution?
Aucun commentaire:
Enregistrer un commentaire