我自己寫(xiě)了一些代碼,想知道哪里出了問(wèn)題,更改的代碼已經(jīng)寫(xiě)在里面了
用recursion來(lái)計(jì)算兩點(diǎn)之間最短距離
例如有一個(gè)file
a,b,5 a,c,8 b,d,6 c,d,2 d,e,12 d,f,2 e,g,3 f,g,7
通過(guò)代碼能變成如圖的map
讀取文件和生成map的代碼已經(jīng)寫(xiě)出來(lái)了剩下的就是如何計(jì)算a到g的最短距離,有點(diǎn)懵逼,沒(méi)啥思路,已寫(xiě)代碼如下哈
""" Graph search to find shortest path between two cities. A road map is represented as a directed graph. Edges represent road segments and are labeled with distances. Nodes represent cities. Wne use depth first search to find the shortest distance between two cities. During the depth-first search from start to end, we compute a 'shortest known distance to here from start' attribute for each node. After completion of depth first search, destination city should be labeled with the shortest distance from the start city. """ import argparse def read_distances(map_file): """Read a distance table from a named file into a dict mapping sources to lists of (destination, distance) pairs. Args: map_file: A readable text file in which each line either begins with # (indicating a comment line) or is of the form from location, to location, distance or time, for example Minis Tirith,Cair Andros,5 indicating one can travel from Minis Tirith to Cair Andros in 5.0 hours. Returns: Dict in which each entry d[from] is a list [(to, cost), (to, cost), ... ] where from is a location name, to is a location name, and cost is time or distance as a floating point number. If x,y,z appears in the input file, then we should have both d[x] contains (y,z) and d[y] contains (x,z), i.e., we assume that roads are bi-directional. """ connections = dict() for line in map_file: line = line.strip() if line.startswith("#") or line=="" : # print("Skipping comment: ", line) continue ## Discard and go on to next # print("Processing line: ", line) fields = line.split(",") place_from = fields[0] place_to = fields[1] cost = float(fields[2]) if not (place_from in connections): connections[place_from] = [ ] connections[place_from].append( (place_to, cost) ) if not (place_to in connections): connections[place_to] = [ ] connections[place_to].append( (place_from, cost) ) return connections def show_roads(roads): """Print roads from dict (for debugging). Args: roads: A dict in which roads[Chicago] == [("Atlanta", 30.0), ("Austin", 25.0)] means that there is a 30.0 mile road from Chicago to Atlanta and a 25.0 mile road from Chicago to Austin. Returns: nothing Effects: Prints a textual representation of the road connections """ for from_place in roads: print(from_place + ":") for hop in roads[from_place]: to_place, dist = hop print("\t->" + to_place + " (" + str(dist) + ")") def dfs(place, dist_so_far, roads, distances): """Depth-first search, which may continue from from_place if dist_so_far is the shortest distance at which it has yet been reached. Args: place: Currently searching from here dist_so_far: Distance at which from_place has been reached this time (which may not be the shortest path to from_place) roads: dict mapping places to lists of hops of the form (place, hop-distance) distances: dict mapping places to the shortest distance at which they have been reached so far (up to this time). """ distances = [] dist_so_far = distances[place] if place not in distances: distances[place] = dist_so_far for city,dist in road[place]: for i in city: dfs(i,dist_so_far,roads,distances) else: if distances[place]<=dist_so_far: distances[place] = dist_so_far #FIXME # Consider cases: # - We've never been at place before (so it's not in distances) # - We've been at place before, on a path as short as this one (in distances) # - We've been here before, but this way is shorter (dist_so_far) # Consider which are base cases, and which require recursion. # For the cases that require recursion, what is the progress step? def main(): """ Main program gets city pair and map file name, reports distance or reports lack of connectivity. """ parser = argparse.ArgumentParser( description="Find shortest route in road network") parser.add_argument('from_place', help = "Starting place (quoted if it contains blanks)") parser.add_argument('to_place', help = "Destination place (quoted if it contains blanks)") parser.add_argument('map_file', type=argparse.FileType('r'), help = "Name of file containing road connections and distances") args = parser.parse_args() start_place = args.from_place destination = args.to_place roads = read_distances(args.map_file) if not start_place in roads: print("Start place ", start_place, " is not on the map") exit(1) if not destination in roads: print("Destination ", destination, " is not on the map") exit(1) distances = { } dfs(start_place, 0.0, roads, distances ) if destination in distances : print("Distance from {} to {} is {}".format( start_place,destination, distances[destination])) else: print("You can't get from {} to {}".format(start_place, destination)) if __name__ == "__main__": main()
擁有18年軟件開(kāi)發(fā)和IT教學(xué)經(jīng)驗(yàn)。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項(xiàng)目經(jīng)理、高級(jí)軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
代碼里提示說(shuō)使用深度搜索優(yōu)先算法(depth first search)了。一條路走到底,每一步選擇一個(gè)未走過(guò)的點(diǎn)。
上周通過(guò)office hour問(wèn)過(guò)GTF之后自己成功那個(gè)寫(xiě)出來(lái)一個(gè)代碼可以運(yùn)行
def?dfs(place,?dist_so_far,?roads,?distances): ????"""Depth-first?search,?which?may?continue?from?from_place?if?dist_so_far???? ????????is?the?shortest?distance?at?which?it?has?yet?been?reached.?? ???????Args:? ??????????place:?Currently?searching?from?here ??????????dist_so_far:??Distance?at?which?from_place?has?been?reached? ??????????????this?time?(which?may?not?be?the?shortest?path?to?from_place) ??????????roads:??dict?mapping?places?to?lists?of?hops?of?the?form?(place,?hop-distance) ??????????distances:?dict?mapping?places?to?the?shortest?distance?at?which?they? ???????????????have?been?reached?so?far?(up?to?this?time).? ????""" ???? ????if?place?not?in?distances: ????????distances[place]?=?dist_so_far ????????for?city,dist?in?roads[place]: ????????????dfs(city,dist_so_far+dist,roads,distances) ????else: ????????if?distances[place]?>?dist_so_far: ????????????????distances[place]?=?dist_so_far ????????????????for?city,dist?in?roads[place]: ????????????????????dfs(city,dist_so_far+dist,roads,distances)
最后得到將近滿(mǎn)分的評(píng)分,缺憾在于可以將兩個(gè)for loop變成一個(gè)。標(biāo)準(zhǔn)答案professor還沒(méi)有上傳,上傳后我也會(huì)更新上來(lái)。