python禁忌搜索算法源代码
时间: 2023-11-21 07:57:11 浏览: 31
以下是Python禁忌搜索算法的示例代码:
```python
import random
# 禁忌搜索算法
def tabu_search(cost_func, neighbor_func, tabu_len=15, max_iter=100):
# 初始化
best_solution = neighbor_func()
best_cost = cost_func(best_solution)
tabu_list = [best_solution]
for i in range(max_iter):
# 获取邻居解
neighbor_solutions = [neighbor_func() for _ in range(10)]
# 选择最优解
neighbor_costs = [cost_func(s) for s in neighbor_solutions]
best_neighbor_cost = min(neighbor_costs)
best_neighbor_index = neighbor_costs.index(best_neighbor_cost)
best_neighbor_solution = neighbor_solutions[best_neighbor_index]
# 更新最优解
if best_neighbor_cost < best_cost and best_neighbor_solution not in tabu_list:
best_solution = best_neighbor_solution
best_cost = best_neighbor_cost
# 更新禁忌表
tabu_list.append(best_neighbor_solution)
if len(tabu_list) > tabu_len:
tabu_list.pop(0)
return best_solution, best_cost
# 示例函数:求解一元二次方程的最小值
def quadratic_cost(x):
return x**2 - 4*x + 3
# 示例函数:获取一元二次方程的随机解
def quadratic_neighbor():
return random.uniform(-10, 10)
# 运行禁忌搜索算法
best_solution, best_cost = tabu_search(quadratic_cost, quadratic_neighbor)
print("最优解:", best_solution)
print("最优代价:", best_cost)
```