0

This is what my code looks like when simplified:

# This function returns some value depending on the index (integer)
# with which it is called.
def funct(index):
    value <-- some_process[index]
    # Return value for this index.
    return value

where the indexes allowed are stored in a list:

# List if indexes.
x = [0,1,2,3,...,1000]

I need to find the x index that returns the minimum value for funct. I could just apply a brute force approach and loop through the full x list storing all values in new a list and then simply find the minimum with np.argmin():

list_of_values = []
for indx in x:
    f_x = funct(x)
    list_of_values.append(f_x)

min_value = np.argmin(list_of_values)

I've tried this and it works, but it becomes quite expensive when x has too many elements. I'm looking for a way to optimize this process.

I know that scipy.optimize has some optimization functions to find a global minimum like anneal and basin-hopping but I've failed to correctly apply them to my code.

Can these optimization tools be used when I can only call a function with an integer (the index) or do they require the function to be continuous?

4

1 回答 1

4

python 内置min接受一个key函数:

min_idx = min(x, key=funct)
min_val = funct(min_idx)

这为您提供了一个 O(n) 解决方案,与您将要在 python 中实现一样。

于 2013-10-02T19:11:22.297 回答