第六周总结

本次我基本完成了地铁查询系统的web端内容,但成品仍有很多瑕疵,只满足了最基本的内容功能,设计代码如下:

def get_station_info(station_name):

    sql = "SELECT * FROM stations WHERE name='%s'" % station_name

    result = execute_sql(sql)

    if len(result) == 0:

        return None

    else:

        return result[0]

 

 

import heapq

 

def dijkstra(graph, start, end):

    # 记录每个节点的距离和前驱节点

    distances = {start: 0}

    path = {}

 

    # 将起点加入队列

    heap = []

    heapq.heappush(heap, (0, start))

 

    # 遍历所有节点

    while heap:

        (current_distance, current_node) = heapq.heappop(heap)

 

        # 如果当前节点已经访问过,则跳过

        if current_node in path: continue

 

        # 将当前节点标记为已访问

        path[current_node] = current_distance

 

        # 如果到达终点,则返回最短路径长度

        if current_node == end:

            return current_distance

 

        # 遍历当前节点的邻居节点

        for neighbor, distance in graph[current_node].items():

            new_distance = current_distance + distance

 

            # 如果通过当前节点到邻居节点的距离更短,则更新距离和前驱节点

            if neighbor not in distances or new_distance < distances[neighbor]:

                distances[neighbor] = new_distance

                heapq.heappush(heap, (new_distance, neighbor))

 

    # 如果无法

达终点,则返回无穷大

    return float('inf')

 

def calculate_distance(from_station, to_station):

    from_station_info = get_station_info(from_station)

    to_station_info = get_station_info(to_station)

    

    if not from_station_info or not to_station_info:

        return None

 

    graph = build_graph()

    distance = dijkstra(graph, from_station_info["id"], to_station_info["id"])

    return distance

 

def build_graph():

    graph = {}

    sql = "SELECT * FROM graph"

    result = execute_sql(sql)

    for row in result:

        from_station_id, to_station_id, distance = row["from_station_id"], row["to_station_id"], row["distance"]

 

        # 构建起点到终点的连接关系和权重

        if from_station_id not in graph:

            graph[from_station_id] = {}

        graph[from_station_id][to_station_id] = distance

 

        # 构建终点到起点的连接关系和权重

        if to_station_id not in graph:

            graph[to_station_id] = {}

        graph[to_station_id][from_station_id] = distance

 

    return graph

posted @ 2023-06-10 20:39  宋瑞哲  阅读(30)  评论(0)    收藏  举报