首页 新闻 搜索 专区 学院

最近写了一个python的练习题,涉及到很多的宽度遍历和深度遍历

0
悬赏园豆:5 [已解决问题] 解决于 2015-04-27 09:36

class Train:
'''
classdocs
'''


def __init__(self, graph, distance, maximum, exactly):
'''
Constructor
'''

# 'AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7'
self.graph = graph
# 'A-E-B-C-D'
self.distance = distance
# 'C'
self.maximum = maximum
# 'A-C'
self.exactly = exactly


# 生成字典
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

def getDistance(self):
'''The distance of the route'''
distance = self.distance
str = distance.replace('-', '').replace(' ', '')
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


def getNumberOfMaximumStops(self):
'''The number of trips starting at C and ending at C with a maximum of 3 stops.'''
station = self.maximum
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)


def getNumberOfExactlyFourStops(self):
'''The number of trips starting at A and ending at C with exactly 4 stops.'''
search = self.exactly
searchKeys = stationObj[search[0]].keys()
counts = self.exactlyFour(searchKeys, search[2], stationObj, 1, 0, 4)
return counts

def exactlyFour(self, ardata, dest, dict, lvl, count, totallvl):
if lvl > totallvl or len(ardata) == 0:
return count
arnext = []
for el in ardata:
if lvl < totallvl:
# 取出下一级
arnext.extend(dict[el].keys())
else:
if el is dest:
count = count + 1
return self.exactlyFour(set(arnext), dest, dict, lvl + 1, count, totallvl)

def getShortestRoute(self):
return ''

问题补充:

题目是,给你一个视图,Graph: AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7

求:

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.

 

我的思路是构造我要用到的数据结构{'A': {'B': '5', 'E': '7', 'D': '5'}, 'C': {'E': '2', 'D': '8'}, 'B': {'C': '4'}, 'E': {'B': '3'}, 'D': {'C': '8', 'E': '6'}}

1-5问很简单

6-7问很相似,都用到了宽度遍历

目前在做8-9问,都要用到深度遍历,有思路但是现在还没想到怎么实现

 

 

 

 

def getShortestRoute(source,ardata,dict,dest,dict):
# 存储距离
result = []
for el in ardata:
if el is dest:
# TODO:此条线结束,记录下此条线的距离
pass
else:
result.append(el)

Klaus.Fenng的主页 Klaus.Fenng | 初学一级 | 园豆:199
提问于:2015-04-24 17:16
< >
分享
最佳答案
0
def getNumberLessThanThirty(asource,sdest,scurrent,ardata,dict,distance):
    # 停止条件:距离小于30,并且当前节点为sdest
    if distance < 30 and len(asource) > 0  and scurrent is sdest:
        asource.append(scurrent)
        ardata.append(asource)
    else:
        achild = dict[scurrent].keys()
        for schild in achild:
            for s in dict[schild].keys():
                atemp = asource  + [schild] + [s]
                if len(atemp) <= 1:
                    length = 0
                else:
                    route = ''
                    for i in atemp:
                        route = route + i
                    length = getDistance(route)
                    return getNumberLessThanThirty(atemp,sdest,schild,ardata,dict,length)
Klaus.Fenng | 初学一级 |园豆:199 | 2015-04-25 17:43

测试用例

#!/usr/bin/env python
#!-*- coding:UTF-8 -*-


from huawei.demo import Demo
import unittest

class Test(unittest.TestCase):
                         
    def testValue01(self):
        self.demo = Demo()
        list = self.demo.truncate('dododododonotlikemeordoodolikemedowithme','likeme')
        self.assertEqual(list,'dowithme')                           
        
                                    
if __name__ == "__main__":
    unittest.main()
Klaus.Fenng | 园豆:199 (初学一级) | 2015-04-27 09:58
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册