class Path(object): def __init__(self,path,cost1,cost2): self.__path = path self.__cost1 = cost1 self.__cost2 = cost2 #路径上最后一个节点 def getLastNode(self): return self.__path[-1] #获取路径路径 @property def path(self): return self.__path #判断node是否为路径上最后一个节点 def isLastNode(self, node): return node == self.getLastNode() #增加加点和成本产生一个新的path对象 def addNode(self, node, price1,price2): return Path(self.__path+[node],self.__cost1+ price1,self.__cost2+ price2) #输出当前路径 def printPath(self): global num #将num作为循环次数,即红绿灯数量 global distance num = 0 for n in self.__path: if self.isLastNode(node=n): print(n) else: print(n, end="->") num += 1 print("全程约为 {:.4}公里".format(str(self.__cost1))) print("时间大约为 {}分钟".format(str(self.__cost2))) print("需要经过{}个红绿灯".format(num)) distance = self.__cost1 #获取路径总成本的只读属性 @property def travelCost1(self): return self.__cost1 @property def travelCost2(self): return self.__cost2 class DirectedGraph(object): def __init__(self, d): if isinstance(d, dict): self.__graph = d else: self.__graph = dict() print('Sth error') def __generatePath(self, graph, path, end, results): #current = path[-1] current = path.getLastNode() if current == end: results.append(path) else: for n in graph[current]: #if n not in path: if n not in path.path: #self.__generatePath(graph, path + [n], end, results) self.__generatePath(graph, path.addNode(n,self.__graph[path.getLastNode()][n][0],self.__graph[path.getLastNode()][n][1]),end, results) #self.__gener给该代码加一个可以保存输入记录并且能够查询显示的功能
时间: 2024-02-10 17:17:23 浏览: 54
可以通过添加一个字典来保存输入记录,例如在 DirectedGraph 类的构造函数中添加以下代码:
```
self.__input_records = {"graph": d}
```
然后在需要查询显示输入记录时,可以添加以下方法:
```
def showInputRecords(self):
print("Input Records:")
for key, value in self.__input_records.items():
print("{}: {}".format(key, value))
```
这样就可以在需要时调用 showInputRecords() 方法来显示输入记录。
相关问题
优化该代码class Path(object): def __init__(self,path,cost1,cost2): self.__path = path self.__cost1 = cost1 self.__cost2 = cost2 #路径上最后一个节点 def getLastNode(self): return self.__path[-1] #获取路径路径 @property def path(self): return self.__path #判断node是否为路径上最后一个节点 def isLastNode(self, node): return node == self.getLastNode() #增加加点和成本产生一个新的path对象 def addNode(self, node, price1,price2): return Path(self.__path+[node],self.__cost1+ price1,self.__cost2+ price2) #输出当前路径 def printPath(self): global num #将num作为循环次数,即红绿灯数量 global distance num = 0 for n in self.__path: if self.isLastNode(node=n): print(n) else: print(n, end="->") num += 1 print("全程约为 {:.4}公里".format(str(self.__cost1))) print("时间大约为 {}分钟".format(str(self.__cost2))) print("需要经过{}个红绿灯".format(num)) distance = self.__cost1 #获取路径总成本的只读属性 @property def travelCost1(self): return self.__cost1 @property def travelCost2(self): return self.__cost2 class DirectedGraph(object): def __init__(self, d): if isinstance(d, dict): self.__graph = d else: self.__graph = dict() print('Sth error') def __generatePath(self, graph, path, end, results): #current = path[-1] current = path.getLastNode() if current == end: results.append(path) else: for n in graph[current]: #if n not in path: if n not in path.path: #self.__generatePath(graph, path + [n], end, results) self.__generatePath(graph, path.addNode(n,self.__graph[path.getLastNode()][n][0],self.__graph[path.getLastNode()][n][1]),end, results) #self.__generatePath(graph,使其能够保存输入记录并且能够查询和显示
可以考虑以下优化:
1. 在 `Path` 类中,可以将 `getLastNode()` 方法改为直接返回 `self.__path[-1]`,因为这个方法只被 `addNode()` 方法调用,而 `addNode()` 方法中也可以直接使用 `self.__path[-1]`。
2. 在 `Path` 类中,可以将 `isLastNode()` 方法改为直接比较 `node` 和 `self.__path[-1]`,因为这个方法只被 `printPath()` 方法调用,而 `printPath()` 方法中也可以直接比较。
3. 在 `Path` 类中,可以将 `printPath()` 方法中的 `global` 声明去掉,因为在该方法中没有使用到任何全局变量。
4. 在 `Path` 类中,可以将 `distance` 变量改为实例变量,即在 `__init__()` 方法中初始化为 0,并在 `printPath()` 方法中使用 `self.__cost1` 赋值。
5. 在 `DirectedGraph` 类中,可以将 `__graph` 变量改为实例变量,即在 `__init__()` 方法中初始化为空字典,并在需要使用时直接使用 `self.__graph`。
下面是修改后的代码:
```
class Path(object):
def __init__(self, path, cost1, cost2):
self.__path = path
self.__cost1 = cost1
self.__cost2 = cost2
self.__distance = 0 # 路径总长度,初始为 0
@property
def path(self):
return self.__path
def getLastNode(self):
return self.__path[-1]
def isLastNode(self, node):
return node == self.__path[-1]
def addNode(self, node, price1, price2):
return Path(self.__path + [node], self.__cost1 + price1, self.__cost2 + price2)
def printPath(self):
num = 0
for n in self.__path:
if self.isLastNode(n):
print(n)
else:
print(n, end="->")
num += 1
print("全程约为 {:.4}公里".format(str(self.__cost1)))
print("时间大约为 {}分钟".format(str(self.__cost2)))
print("需要经过{}个红绿灯".format(num))
self.__distance = self.__cost1
@property
def travelCost1(self):
return self.__cost1
@property
def travelCost2(self):
return self.__cost2
class DirectedGraph(object):
def __init__(self, d):
if isinstance(d, dict):
self.__graph = d
else:
self.__graph = dict()
print('Sth error')
def __generatePath(self, graph, path, end, results):
current = path.getLastNode()
if current == end:
results.append(path)
else:
for n in graph[current]:
if n not in path.path:
results = self.__generatePath(graph, path.addNode(n, graph[path.getLastNode()][n][0], graph[path.getLastNode()][n][1]), end, results)
return results
```
class Path(object): def __init__(self,path,distancecost,timecost): self.__path = path self.__distancecost = distancecost self.__timecost = timecost #路径上最后一个节点 def getLastNode(self): return self.__path[-1] #获取路径路径 @property def path(self): return self.__path #判断node是否为路径上最后一个节点 def isLastNode(self, node): return node == self.getLastNode() #增加加点和成本产生一个新的path对象 def addNode(self, node, dprice, tprice): return Path(self.__path+[node],self.__distancecost + dprice,self.__timecost + tprice) #输出当前路径 def printPath(self): for n in self.__path: if self.isLastNode(node=n): print(n) else: print(n, end="->") print(f"最短路径距离(self.__distancecost:.0f)m") print(f"红绿路灯个数(self.__timecost:.0f)个") #获取路径总成本的只读属性 @property def dCost(self): return self.__distancecost @property def tCost(self): return self.__timecost class DirectedGraph(object): def __init__(self, d): if isinstance(d, dict): self.__graph = d else: self.__graph = dict() print('Sth error') #通过递归生成所有可能的路径 def __generatePath(self, graph, path, end, results, distancecostIndex, timecostIndex): current = path.getLastNode() if current == end: results.append(path) else: for n in graph[current]: if n not in path.path: self.__generatePath(graph, path.addNode(n,self.__graph[path.getLastNode()][n][distancecostIndex][timecostIndex]), end, results, distancecostIndex, timecostIndex) #搜索start到end之间时间或空间最短的路径,并输出 def __searchPath(self, start, end, distancecostIndex, timecostIndex): results = [] self.__generatePath(self.__graph, Path([start],0,0), end, results,distancecostIndex,timecostIndex) results.sort(key=lambda p: p.distanceCost) results.sort(key=lambda p: p.timeCost) print('The {} shortest path from '.format("spatially" if distancecostIndex==0 else "temporally"), start, ' to ', end, ' is:', end="") print('The {} shortest path from '.format("spatially" if timecostIndex==0 else "temporally"), start, ' to ', end, ' is:', end="") results[0].printPath() #调用__searchPath搜索start到end之间的空间最短的路径,并输出 def searchSpatialMinPath(self,start, end): self.__searchPath(start,end,0,0) #调用__searc 优化这个代码
这段代码中可以进行如下优化:
1. 将类属性的命名改为下划线开头的私有属性,避免外部直接修改属性值,可以使用@property装饰器来获取属性的值。
2. 可以将类的构造函数中的参数改为可选参数,避免在初始化时需要传入参数,可以在需要时再传入参数。
3. 在递归函数的参数中加入默认值,避免在调用递归函数时需要传入所有参数。
4. 可以使用f-string格式化输出语句,代码更加简洁易读。
5. 可以使用列表推导式对列表进行过滤。
6. 在搜索最短路径时可以使用heapq模块的堆排序来优化效率。
优化后的代码如下:
```python
import heapq
class Path(object):
def __init__(self, path = [], distance_cost = 0, time_cost = 0):
self._path = path
self._distance_cost = distance_cost
self._time_cost = time_cost
def get_last_node(self):
return self._path[-1]
def is_last_node(self, node):
return node == self.get_last_node()
def add_node(self, node, d_price, t_price):
return Path(self._path + [node], self._distance_cost + d_price, self._time_cost + t_price)
def print_path(self):
for n in self._path:
print(n, end="->" if not self.is_last_node(n) else "\n")
print(f"最短路径距离({self._distance_cost:.0f}m)")
print(f"红绿路灯个数({self._time_cost:.0f})个")
@property
def d_cost(self):
return self._distance_cost
@property
def t_cost(self):
return self._time_cost
class DirectedGraph(object):
def __init__(self, d = {}):
if isinstance(d, dict):
self._graph = d
else:
self._graph = dict()
print('Something went wrong!')
def __generate_path(self, graph, path, end, results, distance_cost_index=0, time_cost_index=0):
current = path.get_last_node()
if current == end:
results.append(path)
else:
for n in graph[current]:
if n not in path._path:
self.__generate_path(graph, path.add_node(n, self._graph[path.get_last_node()][n][distance_cost_index][time_cost_index]), end, results, distance_cost_index, time_cost_index)
def __search_path(self, start, end, distance_cost_index=0, time_cost_index=0):
results = []
self.__generate_path(self._graph, Path([start], 0, 0), end, results, distance_cost_index, time_cost_index)
results = heapq.nsmallest(1, results, key=lambda p: (p.d_cost, p.t_cost))
print(f"The {'spatially' if distance_cost_index==0 else 'temporally'} shortest path from {start} to {end} is:")
results[0].print_path()
def search_spatial_min_path(self, start, end):
self.__search_path(start, end, 0, 0)
def search_temporal_min_path(self, start, end):
self.__search_path(start, end, 1, 1)
```
阅读全文