I have a an algorithm that goes according to the following logic:
Two parameters x
and y
take values in A={1,2,3,4}
and B={'a','b','c'}
, respectively.
Depending on the values of the pairs (x,y)
the algorithm should execute a series corresponding set of steps f_x_y
, but don't think of f_x_y
as a piece of code parametrized by x
and y
. The instructions that need to be executed for (x,y)=(1,'a')
are different from those corresponding to (2,'c')
. Different pieces of code, one for each pair in the Cartesian product of A
and B
. The sets A
and B
are not too large. Their sizes are pretty much as above.
I have considered the following options:
Option 1: An implementation using if
s.
if x == 1:
if y == 'a':
f_1_a
elif y == 'b':
f_1_b # Remember that it is not a function, but an entirely different piece of code as f_1_a
# Rest of the cases inside x=1
elif x == 2:
if y == 'a':
f_2_a
# etc.
Option 2: A map from cases to functions.
def f_1_a():
pass
def f_1_b():
pass
# ...
cases = {(1,'a'):f_1_a,(1,'b'):f_1_b,} # ...
cases[(x,y)]()
Question: Which of these, or other alternative, should I prefer?
My gut feeling is that the second would be easy to modify if there are new requirements. I don't have enough experience to tell if any is preferable for being faster.
Aucun commentaire:
Enregistrer un commentaire