0

I have an issue with the use of functions and switcher in python: I have this production cost function:

def fcostoproduccion (X,periodo):
if X > 0:
    switcher = {
            1:  200 + 15 * X,
            2:  100 + 20 * X,
            3:  100 + 4 * (X ** (1 / 2)),
            4:  100 + 3 * X,
            5:  150 + 6 * X,
            6:  200 + 12 * (X ** (1 / 2)),
            7:  200 + 15 * X,
            8:  100 + 10 * X,
            9:  100 + 6 * (X ** (1 / 2)),
            10: 200 + 5 * (X ** (1 / 2)),
            11: 100 + 10 * X,
            12: 150 + 6 * X

            }
return

And at the end I'm trying to look for the value:

  for l in range(j+1, k+1):
    Ordenar = O[l] 
    Produccion = fcostoproduccion(Demanda, l)

I know I'm making a mistake but don't know how to solve it. Thanks in advance.

2 Answers2

0

If I understand correctly, you need the behavior of a good old switch-case. Unfortunately, there is no built-in switch case in python. The preferred way is to use a dictionary. Thus, you are really close. Try replacing your return statement:

return switcher[X]

Note that you want to return it only if X > 1. therefore, make sure to indent your return statement and handle the else case as you want.

Note that your second argument seems totally useless in this case. So you may want to remove periodo.

scharette
  • 9,437
  • 8
  • 33
  • 67
0

A couple of things with the function fcostoproduccion:

  1. It always returns None
  2. It has no side effect
  3. It makes use of only the first argument passed into it (i.e. the paramenter periodo is unsused in the function).

It is hard to discern your intention with the function however I guess

  1. you want to compute a value based on X
  2. The formular to compute the desired return value varies for different values of X hence the dictionary switcher.

Based on the above assumtions, you can modify the function fcostoproduccion as follows:

def fcostoproduccion(X):
    switcher = {
    1:  200 + 15 * X,
    2:  100 + 20 * X,
    3:  100 + 4 * (X ** (1 / 2)),
    4:  100 + 3 * X,
    5:  150 + 6 * X,
    6:  200 + 12 * (X ** (1 / 2)),
    7:  200 + 15 * X,
    8:  100 + 10 * X,
    9:  100 + 6 * (X ** (1 / 2)),
    10: 200 + 5 * (X ** (1 / 2)),
    11: 100 + 10 * X,
    12: 150 + 6 * X
    }
    return switcher[X] if X in switcher else None #Handle cases where X switcher is not defined for X 

>>> [fcostoproduccion(i) for i in range(14)]
[None, 215, 140, 106.92820323027551, 112, 180, 229.39387691339815, 305, 180, 118.0, 215.81138830084188, 210, 222, None]
Xero Smith
  • 1,968
  • 1
  • 14
  • 19