0

I want to do functions dispatch, but there is no switch mechanism in python 3. I learn to use dict for instead like below:

def multiply(m,n,o):
    return m*n*o    
def add(m,n):
    return m+n
my_math = { "+":add,
            "*":multiply}

However, my functions have different parameters. How do I pass my parameters through my_math[op](...)? Thanks~

auxo
  • 23
  • 3

2 Answers2

0

I have try to re-design my code as follow, and it should work.

c = [1,2,3]
def multiply(a):
    return a[0]*a[1]*a[2]
def add(b):
    return b[0]+b[1]
my_math = { "+":add,
            "*":multiply}
print(str(my_math["+"](c)))
print(str(my_math["*"](c)))
auxo
  • 23
  • 3
0

I thought this well be better.

c = [1,2,3]
def multiply(x, y, z):
    return x * y * z
def add(x, y):
    return x + y
my_math = { "+":add,
            "*":multiply}
print(str(my_math["+"](*c)))
print(str(my_math["*"](*c)))

or, one more step:

c = [1,2,3]
def multiply(*n):
    return reduce(lambda x, y: x * y, n)
def add(*n):
    return sum(n)
my_math = { "+":add,
            "*":multiply}
print(str(my_math["+"](*c)))
print(str(my_math["*"](*c)))