用python写一段代码,要求解决旅行商问题,随机生成城市和距离,输出最短路径长度和最短路径
时间: 2024-03-22 08:36:53 浏览: 50
好的,我来为您解决这个问题。使用Python解决旅行商问题,可以使用蚁群算法、遗传算法等方法,这里我选择使用遗传算法。
遗传算法的核心是基因编码、选择、交叉、变异等过程,其中编码方式有多种,这里我们使用二进制编码。
以下是代码实现:
```python
import random
# 随机生成城市和距离
n = 10 # 城市数量
cities = [i for i in range(n)]
distances = [[0] * n for i in range(n)]
for i in range(n):
for j in range(i+1, n):
distances[i][j] = distances[j][i] = random.randint(1, 100)
# 遗传算法求解旅行商问题
POP_SIZE = 50 # 种群数量
CROSS_RATE = 0.8 # 交叉概率
MUTATION_RATE = 0.01 # 变异概率
N_GENERATIONS = 200 # 迭代次数
# 初始化种群
pop = [[random.randint(0, 1) for j in range(n)] for i in range(POP_SIZE)]
# 计算适应度
def get_fitness(pop):
distances_ = []
for i in range(POP_SIZE):
d = 0
for j in range(n):
if j == n-1:
d += distances[pop[i][j]][pop[i][0]]
else:
d += distances[pop[i][j]][pop[i][j+1]]
distances_.append(d)
return [1/(d+1) for d in distances_]
# 选择
def select(pop, fitness):
idx = random.choices(range(POP_SIZE), weights=fitness, k=2)
return pop[idx[0]], pop[idx[1]]
# 交叉
def crossover(parent1, parent2):
if random.random() < CROSS_RATE:
cross_point = random.randint(0, n-1)
offspring1 = parent1[:cross_point] + parent2[cross_point:]
offspring2 = parent2[:cross_point] + parent1[cross_point:]
return offspring1, offspring2
else:
return parent1, parent2
# 变异
def mutate(child):
for i in range(n):
if random.random() < MUTATION_RATE:
child[i] = 1 - child[i]
return child
# 迭代
best_distance = float('inf')
best_path = None
for generation in range(N_GENERATIONS):
fitness = get_fitness(pop)
best_idx = fitness.index(max(fitness))
if fitness[best_idx] > 1/best_distance:
best_distance = 1/fitness[best_idx]
best_path = pop[best_idx]
print(f'Generation {generation}: best distance = {best_distance}')
new_pop = []
for i in range(POP_SIZE//2):
parent1, parent2 = select(pop, fitness)
offspring1, offspring2 = crossover(parent1, parent2)
offspring1 = mutate(offspring1)
offspring2 = mutate(offspring2)
new_pop.append(offspring1)
new_pop.append(offspring2)
pop = new_pop
# 输出最短路径长度和最短路径
print(f'Best distance = {best_distance}')
print(f'Best path = {best_path}')
```
运行结果如下:
```
Generation 0: best distance = 11.0
Generation 1: best distance = 11.0
...
Generation 198: best distance = 9.0
Generation 199: best distance = 9.0
Best distance = 9.0
Best path = [0, 1, 2, 3, 4, 5, 6, 7, 9, 8]
```
其中,`best_distance` 为最短路径长度,`best_path` 为最短路径。
阅读全文