Ad
Python Elif Optimization Problems
How to optimize this code?
How to optimize this code as short as possible. I am a beginner please help me
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('[]')
Ad
Answer
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))
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad