4

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?

MaPy
  • 505
  • 1
  • 6
  • 9

3 Answers3

4
def functionA(a1, a2, a3):
    results = {
        'case1': a2 / a3 if a3 != 0.0 else a2,
        'case2': 1,
        # ...
    }
    return results[a1]

However, I would advise against this approach as the entire dictionary has to be computed first only to pick up a single value.

Instead, if you really want to use dictionaries and have it also efficient, I would suggest:

myproc = {
    'case1': lambda a2, a3: a2 / a3 if a3 != 0.0 else a2,
    'case2': lambda a2, a3: 1
}

Then:

>>> myproc['case1'](2, 3)
0.6666666666666666
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
1

You can use ternary operator inside your dictionary

def functionA(a1, a2, a3):

    results = {
        'case1': a2 if a3==0 else a2/a3,
        'case2': 1
    }
    return results[a1]

Link : https://repl.it/NRkd

Rahul Verma
  • 2,946
  • 14
  • 27
0

If it's just that one value, you can do it with a simple if-else.

def functionA(a1, a2, a3):

     if a3:
        case1_value = a2/a3
     else: 
        case1_value = a2

    results = {
        'case1': case1_value,
        'case2': 1,
        ...
    }
    return results[a1]

Or create a dvision function with this if-else condition and use it in your dict value.

utengr
  • 3,225
  • 3
  • 29
  • 68