I\'m using scipy.optimize.minimize
to optimize a real-world problem for which the answers can only be integers. My current code looks like this:
Generic function for bruteforce solution. Does somewhat a better job than brute in scipy, since scipy actually runs function with float numbers, not integers only, though range explicitly says so, as Jarad stated
def brute(func, arg_ranges, finish=min):
if isinstance(arg_ranges, dict):
args = {k:np.unique(np.hstack([a for r in rs for a in r]) if isinstance(rs, list) else [a for a in rs]) for k,rs in arg_ranges.items()}
print(args)
return finish([(dict(zip(args.keys(), vs)), func(**dict(zip(args.keys(), vs)))) for vs in itertools.product(*args.values())], key=lambda x: x[1])
elif isinstance(arg_ranges, list):
return finish([(i, func(i)) for r in arg_ranges for i in r], key=lambda x: x[1])
else:
return finish([(i, func(i)) for i in arg_ranges], key=lambda x: x[1])
print(brute(lambda x,y: x / (y + 2), {'x':[range(1,5,2), range(0,6,1)], 'y':range(2,5,1)}))