# 求大神帮忙写个深度遍历，python语言的

0

Graph: AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7

dict = {'A': {'B': '5', 'E': '7', 'D': '5'}, 'C': {'E': '2', 'D': '8'}, 'B': {'C': '4'}, 'E': {'B': '3'}, 'D': {'C': '8', 'E': '6'}}

Problem one: Trains

The local commuter railroad services a number of towns in Kiwiland. Because of monetary concerns, all of the tracks are 'one-way.' That is, a route from Kaitaia to Invercargill does not imply the existence of a route from Invercargill to Kaitaia. In fact, even if both of these routes do happen to exist, they are distinct and are not necessarily the same distance!

The purpose of this problem is to help the railroad provide its customers with information about the routes. In particular, you will compute the distance along a certain route, the number of different routes between two towns, and the shortest route between two towns.

Input: A directed graph where a node represents a town and an edge represents a route between two towns. The weighting of the edge represents the distance between the two towns. A given route will never appear more than once, and for a given route, the starting and ending town will not be the same town.

Output: For test input 1 through 5, if no such route exists, output 'NO SUCH ROUTE'. Otherwise, follow the route as given; do not make any extra stops! For example, the first problem means to start at city A, then travel directly to city B (a distance of 5), then directly to city C (a distance of 4).
1. The distance of the route A-B-C.
2. The distance of the route A-D.
3. The distance of the route A-D-C.
4. The distance of the route A-E-B-C-D.
5. The distance of the route A-E-D.
6. The number of trips starting at C and ending at C with a maximum of 3 stops. In the sample data below, there are two such trips: C-D-C (2 stops). and C-E-B-C (3 stops).
7. The number of trips starting at A and ending at C with exactly 4 stops. In the sample data below, there are three such trips: A to C (via B,C,D); A to C (via D,C,D); and A to C (via D,E,B).
8. The length of the shortest route (in terms of distance to travel) from A to C.
9. The length of the shortest route (in terms of distance to travel) from B to B.
10. The number of different routes from C to C with a distance of less than 30. In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC, CDEBC, CEBCEBC, CEBCEBCEBC.

Test Input:
For the test input, the towns are named using the first few letters of the alphabet from A to D. A route between two towns (A to B) with a distance of 5 is represented as AB5.
Graph: AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7
Expected Output:
Output #1: 9
Output #2: 5
Output #3: 13
Output #4: 22
Output #5: NO SUCH ROUTE
Output #6: 2
Output #7: 3
Output #8: 9
Output #9: 9
Output #10: 7

Klaus.Fenng | 初学一级 | 园豆：199

1
```def getShortestDistanceWithDiff(self, shortestDiff):
'''
The length of the shortest route (in terms of distance to travel) from A to C
@param {[string]} shortestDiff [a route like:'AC']
'''
shortestDiff = shortestDiff.strip()
ardata = []
self.getShortestRouteWithDiff([], shortestDiff[1], shortestDiff[0], ardata, stationObj)
distanceArr = []
# ardata中存储的为路线的数组
for ar in ardata:
route = ''
for i in ar:
route = route + i
distance = self.getDistance(route)
distanceArr.append(distance)
sortData = sorted(enumerate(distanceArr), key=lambda x:x[1])
return sortData[0][1]

def getShortestRouteWithDiff(self,asource,sdest,scurrent,ardata,dict):
'''
递归（求两座城镇之间的最短距离，起始点不同）
'''
if scurrent == sdest:
asource.append(scurrent)
ardata.append(asource)
elif scurrent in asource:
pass
else:
achild = dict[scurrent].keys()
for schild in achild:
atemp = asource + [scurrent]
self.getShortestRouteWithDiff(atemp,sdest,schild,ardata,dict)```
Klaus.Fenng | 初学一级 |园豆：199 | 2015-04-25 17:29
```def getShortestRouteWithSameStation(self,shortestSame):
'''
The length of the shortest route (in terms of distance to travel) from B to B.
@param {[string]} shortestSame [a station like:'B']
'''
shortestSame = shortestSame.strip()
ardata = []
self.getShortestRouteWithSame([],shortestSame,shortestSame,ardata,stationObj,True)
distanceArr = []
try:
for ar in ardata:
route = ''
for i in ar:
route = route + i
distance = self.getDistance(route)
distanceArr.append(distance)
sortData = sorted(enumerate(distanceArr), key=lambda x:x[1])
return sortData[0][1]
except Exception:
return 'NO SUCH ROUTE'

def getShortestRouteWithSame(self,asource,dest,scurrent,ardata,dict,isFirst):
if scurrent is dest and not isFirst:
asource.append(scurrent)
ardata.append(asource)
elif scurrent in asource:
pass
else:
achild = dict[scurrent].keys()
for schild in achild:
atemp = asource + [scurrent]
self.getShortestRouteWithSame(atemp,dest,schild,ardata,dict,False)```

Klaus.Fenng | 园豆：199 (初学一级) | 2015-04-25 17:31
```def __init__(self, graph,):
'''
Constructor
@param {[string]} graph [a graph like:'AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7']
'''

self.graph = graph```

Klaus.Fenng | 园豆：199 (初学一级) | 2015-04-25 17:33
```def getObj(self):
'''
Create data structure from the graph provided
'''
global stationObj

stationObj = {}
graph = self.graph
stationList = graph.strip().split(',')
for list in stationList:
obj = {}
list = list.strip()
obj[list[1]] = list[2]
if stationObj.has_key(list[0]):
tempObj = stationObj[list[0]]
tempObj[list[1]] = list[2]
else:
stationObj[list[0]] = obj
return stationObj```

Klaus.Fenng | 园豆：199 (初学一级) | 2015-04-25 17:34
```def getDistance(self, distance):
'''
The distance of the route
@param {[string]} distance [a route like:'ABC']
'''
str = distance.strip()
objs = {}
lengths = 0
for i in range(len(str)):
if i < len(str) - 1:
objs[str[i]] = str[i + 1]

for j in range(len(str)):
if j < len(str) - 1:
temp = stationObj[str[j]]
value = objs[str[j]]
if not temp.has_key(value):
return 'NO SUCH ROUTE'
else:
lengths = lengths + int(temp[value])
return lengths```

Klaus.Fenng | 园豆：199 (初学一级) | 2015-04-25 17:34
```def getNumberOfMaximumThreeStops(self, maximum):
'''
The number of trips starting at C and ending at C with a maximum of 3 stops.
@param {[string]} maximum [a station like:'C']
'''
station = maximum.strip()
counts = self.traversal(['C'], station, stationObj, 1, 0, 3)
return counts

def traversal(self, ardata, dest, dict, lvl, count, totallvl):
'''遍历'''
if lvl > totallvl or len(ardata) == 0:
return count
else:
arnext = []
for el in ardata:
val = dict[el]
for k in val:
if k == dest:
count = count + 1
else:
arnext.append(k)
return self.traversal(arnext, dest, dict, lvl + 1, count, totallvl)```

Klaus.Fenng | 园豆：199 (初学一级) | 2015-04-25 17:35
```def getNumberOfExactlyFourStops(self, exactlyFour):
'''
The number of trips starting at A and ending at C with exactly 4 stops.
@param {[string]} exactlyFour [a route like:'AC']
'''
search = exactlyFour.strip()
searchKeys = stationObj[search[0]].keys()
counts = self.exactlyFour(searchKeys, search[1], stationObj, 1, 0, 4)
return counts

def exactlyFour(self, ardata, dest, dict, lvl, count, totallvl):
'''
递归（刚好4站）
'''
if lvl > totallvl or len(ardata) == 0:
return count
else:
arnext = []
for el in ardata:
val = dict[el]
for k in val:
if k == dest and (lvl is totallvl):
count = count + 1
else:
arnext.append(k)
return self.exactlyFour(arnext,dest,dict,lvl+1,count,totallvl)```

Klaus.Fenng | 园豆：199 (初学一级) | 2015-04-25 17:35

@Klaus.Fenng: 写错了一点，调用递归是不应有return

Klaus.Fenng | 园豆：199 (初学一级) | 2015-04-25 17:38

@Klaus.Fenng:

``` 1 #-*- coding: utf-8 -*-
2
3 from xml.dom import minidom
4
5
6 def testMiniDom():
7     doc = minidom.parse("employees.xml")
8     root = doc.documentElement
9     employees = root.getElementsByTagName("employee")
10     for employee in employees:
11         nameNode = employee.getElementsByTagName("name")[0]
12         ageNode = employee.getElementsByTagName("age")[0]
13         print (employee.toxml())
14         print (nameNode.nodeName + ":" + nameNode.childNodes[0].nodeValue)
15         print (ageNode.nodeName + ":" + ageNode.childNodes[0].nodeValue)
16
17 def writeXML():
18     impl = minidom.getDOMImplementation()
19     dom = impl.createDocument(None, 'project', None)
20     root = dom.documentElement
21     elem = dom.createElement('ci')
22     elem_value = dom.createTextNode('userver')
23     elem.appendChild(elem_value)
24     root.appendChild(elem)
25     fileHandle = open('employee2.xml','w')
26     dom.writexml(fileHandle, '\n', ' ', '', 'UTF-8')
27     fileHandle.close()
28
29
30 if __name__ == "__main__":
31     testMiniDom()
32     writeXML()```
Klaus.Fenng | 园豆：199 (初学一级) | 2015-05-05 10:26

您需要登录以后才能回答，未注册用户请先注册