优化这段代码:降低这段代码重复率:def crossSol(model): sol_list=copy.deepcopy(model.sol_list) model.sol_list=[] while True: f1_index = random.randint(0, len(sol_list) - 1) f2_index = random.randint(0, len(sol_list) - 1) if f1_index!=f2_index: f1 = copy.deepcopy(sol_list[f1_index]) f2 = copy.deepcopy(sol_list[f2_index]) if random.random() <= model.pc: cro1_index=int(random.randint(0,len(model.demand_id_list)-1)) cro2_index=int(random.randint(cro1_index,len(model.demand_id_list)-1)) new_c1_f = [] new_c1_m=f1.node_id_list[cro1_index:cro2_index+1] new_c1_b = [] new_c2_f = [] new_c2_m=f2.node_id_list[cro1_index:cro2_index+1] new_c2_b = [] for index in range(len(model.demand_id_list)): if len(new_c1_f)<cro1_index: if f2.node_id_list[index] not in new_c1_m: new_c1_f.append(f2.node_id_list[index]) else: if f2.node_id_list[index] not in new_c1_m: new_c1_b.append(f2.node_id_list[index]) for index in range(len(model.demand_id_list)): if len(new_c2_f)<cro1_index: if f1.node_id_list[index] not in new_c2_m: new_c2_f.append(f1.node_id_list[index]) else: if f1.node_id_list[index] not in new_c2_m: new_c2_b.append(f1.node_id_list[index]) new_c1=copy.deepcopy(new_c1_f) new_c1.extend(new_c1_m) new_c1.extend(new_c1_b) f1.nodes_seq=new_c1 new_c2=copy.deepcopy(new_c2_f) new_c2.extend(new_c2_m) new_c2.extend(new_c2_b) f2.nodes_seq=new_c2 model.sol_list.append(copy.deepcopy(f1)) model.sol_list.append(copy.deepcopy(f2)) else: model.sol_list.append(copy.deepcopy(f1)) model.sol_list.append(copy.deepcopy(f2)) if len(model.sol_list)>model.popsize: break
时间: 2023-12-03 15:03:36 浏览: 109
可以将代码重构为以下形式:
```
def crossSol(model):
sol_list = copy.deepcopy(model.sol_list)
model.sol_list = []
while True:
f1_index, f2_index = random.sample(range(len(sol_list)), k=2)
f1, f2 = copy.deepcopy(sol_list[f1_index]), copy.deepcopy(sol_list[f2_index])
if random.random() <= model.pc:
cro1_index, cro2_index = sorted(random.sample(range(len(model.demand_id_list)), k=2))
new_c1_f, new_c1_m, new_c1_b = [], f1.node_id_list[cro1_index:cro2_index+1], []
new_c2_f, new_c2_m, new_c2_b = [], f2.node_id_list[cro1_index:cro2_index+1], []
for index in range(len(model.demand_id_list)):
if len(new_c1_f) < cro1_index:
if f2.node_id_list[index] not in new_c1_m:
new_c1_f.append(f2.node_id_list[index])
else:
new_c1_b.append(f2.node_id_list[index])
if len(new_c2_f) < cro1_index:
if f1.node_id_list[index] not in new_c2_m:
new_c2_f.append(f1.node_id_list[index])
else:
new_c2_b.append(f1.node_id_list[index])
new_c1 = new_c1_f + new_c1_m + new_c1_b
f1.nodes_seq = copy.deepcopy(new_c1)
new_c2 = new_c2_f + new_c2_m + new_c2_b
f2.nodes_seq = copy.deepcopy(new_c2)
model.sol_list.extend([copy.deepcopy(f1), copy.deepcopy(f2)])
else:
model.sol_list.extend([copy.deepcopy(f1), copy.deepcopy(f2)])
if len(model.sol_list) > model.popsize:
break
```
重构后的代码:
- 使用 `random.sample` 代替 `random.randint`,避免重复选择同一个数。
- 简化了变量的初始化和赋值。
- 优化了代码结构,使其更易读懂。
- 避免了使用 `range` 函数的重复调用,提升了代码性能。
阅读全文