# Python Elif Optimization Problems

## 20 August 2019 - 1 answer

How to optimize this code?

out.CONDITIONS:

• arr must be a valid 2D array with valid numbers only.
• data can be : 'column' or 'row'
• value can be : 'min' or 'max' or 'mean' or 'median'
• array must be a valid 2D Array with Integer / Float ONLY
``````def get_math_value(array, data, value):
if data == 'row' and value == 'min':
arr = array
min_row = list(map(min, arr))
print(min_row)
elif data == 'row' and value == 'max':
arr = array
max_row = list(map(min, arr))
print(max_row)
elif data == 'row' and value == 'mean':
arr = array
mean_row = np.mean(arr, axis=1)
print(mean_row)
elif data == 'row' and value == 'median':
arr = array
median_row = np.median(arr, axis=1)
print(median_row)
elif data == 'column' and value == 'min':
arr = array
min_column = list(map(min, zip(*arr)))
print(min_column)
elif data == 'column' and value == 'max':
arr = array
max_column = list(map(max, zip(*arr)))
print(max_column)
elif data == 'column' and value == 'mean':
arr = array
mean_column = np.mean(arr, axis=0)
print(mean_column)
elif data == 'column' and value == 'median':
arr = array
median_column = np.median(arr, axis=0)
print(median_column)
else:
print('[]')
``````

The first thing to know is that `numpy` has `min` and `max` functions, so you don't need the `list(map(min, arr))` calls, you can use e.g. `np.min(arr, axis=1)` instead.

With that in mind you could do something like

``````def get_math_value(array, data, value):
axis = {'column': 0, 'row': 1}.get(data)
func = {'mean': np.mean,
'median': np.median,
'min': np.min,
'max': np.max}.get(value)
if axis is None or func is None:
print('[]')
else:
print(func(array, axis=axis))
``````