遗传算法解决旅行商使用python
时间: 2024-01-10 20:20:29 浏览: 107
遗传算法是一种用于解决优化问题的启发式算法,可以用来解决旅行商问题。下面是一个使用Python实现遗传算法解决旅行商问题的示例:
```python
import random
# 创建一个随机的旅行商问题的城市列表
def create_city_list(num_cities):
city_list = []
for i in range(num_cities):
city_list.append((random.uniform(0, 100), random.uniform(0, 100)))
return city_list
# 计算两个城市之间的距离
def distance(city1, city2):
x1, y1 = city1
x2, y2 = city2
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
# 计算路径的总长度
def total_distance(city_list, path):
total = 0
for i in range(len(path) - 1):
total += distance(city_list[path[i]], city_list[path[i+1]])
return total
# 生成一个随机的路径
def create_random_path(num_cities):
path = list(range(num_cities))
random.shuffle(path)
return path
# 交叉操作
def crossover(parent1, parent2):
child = [-1] * len(parent1)
start = random.randint(0, len(parent1) - 1)
end = random.randint(0, len(parent1) - 1)
if start > end:
start, end = end, start
for i in range(start, end + 1):
child[i] = parent1[i]
j = 0
for i in range(len(parent2)):
if child[j] == -1:
while parent2[i] in child:
i += 1
child[j] = parent2[i]
j += 1
return child
# 变异操作
def mutate(path):
index1 = random.randint(0, len(path) - 1)
index2 = random.randint(0, len(path) - 1)
path[index1], path[index2] = path[index2], path[index1]
return path
# 遗传算法求解旅行商问题
def solve_tsp(city_list, population_size, num_generations):
population = []
for _ in range(population_size):
population.append(create_random_path(len(city_list)))
for _ in range(num_generations):
population = sorted(population, key=lambda x: total_distance(city_list, x))
new_population = population[:population_size // 2]
while len(new_population) < population_size:
parent1 = random.choice(population[:population_size // 2])
parent2 = random.choice(population[:population_size // 2])
child = crossover(parent1, parent2)
if random.random() < 0.1:
child = mutate(child)
new_population.append(child)
population = new_population
best_path = population[0]
best_distance = total_distance(city_list, best_path)
return best_path, best_distance
# 示例用法
city_list = create_city_list(10)
best_path, best_distance = solve_tsp(city_list, 100, 1000)
print("Best path:", best_path)
print("Best distance:", best_distance)
```
这个示例代码使用遗传算法来解决一个包含10个城市的旅行商问题。它首先创建一个随机的城市列表,然后使用遗传算法来找到最短路径。最后,它打印出最佳路径和最佳距离。
阅读全文