降低这段代码的重复率:def checkTimeWindow(route,model,vehicle): timetable=[] departure=0 for i in range(len(route)): if i == 0: next_node_id = route[i + 1] travel_time = int(model.distance_matrix[vehicle.type, next_node_id] /vehicle.free_speed) departure = max(0, model.demand_dict[next_node_id].start_time - travel_time) timetable.append((int(departure), int(departure))) elif 1 <= i <= len(route) - 2: last_node_id = route[i - 1] current_node_id = route[i] current_node = model.demand_dict[current_node_id] travel_time = int(model.distance_matrix[last_node_id, current_node_id] / vehicle.free_speed) arrival = max(timetable[-1][1] + travel_time, current_node.start_time) departure = arrival + current_node.service_time timetable.append((int(arrival), int(departure))) if departure > current_node.end_time: departure = float('inf') break else: last_node_id = route[i - 1] travel_time = int(model.distance_matrix[last_node_id, vehicle.type] / vehicle.free_speed) departure = timetable[-1][1] + travel_time timetable.append((int(departure), int(departure))) if departure<vehicle.end_time: return True else: return False
时间: 2024-03-24 13:40:13 浏览: 58
Timetable-App:这是Android手机的时间表应用程序
可以将重复的代码提取出来,封装成一个函数,如下所示:
```python
def get_travel_time(model, vehicle, start_node_id, end_node_id):
return int(model.distance_matrix[start_node_id, end_node_id] / vehicle.free_speed)
def checkTimeWindow(route, model, vehicle):
timetable = []
departure = 0
for i, node_id in enumerate(route):
if i == 0:
next_node_id = route[i + 1]
travel_time = get_travel_time(model, vehicle, vehicle.type, next_node_id)
departure = max(0, model.demand_dict[next_node_id].start_time - travel_time)
timetable.append((int(departure), int(departure)))
elif 1 <= i <= len(route) - 2:
last_node_id = route[i - 1]
current_node = model.demand_dict[node_id]
travel_time = get_travel_time(model, vehicle, last_node_id, node_id)
arrival = max(timetable[-1][1] + travel_time, current_node.start_time)
departure = arrival + current_node.service_time
timetable.append((int(arrival), int(departure)))
if departure > current_node.end_time:
departure = float('inf')
break
else:
last_node_id = route[i - 1]
travel_time = get_travel_time(model, vehicle, last_node_id, vehicle.type)
departure = timetable[-1][1] + travel_time
timetable.append((int(departure), int(departure)))
if departure >= vehicle.end_time:
return False
return True
```
这样,代码中的重复率就降低了。
阅读全文